Ok, so I have a array like this.
myArray:Array []
myArray.push(Object) // x 4.
I have 4 objects in my array. Then I splice the second one. Leaving me with a array that looks like this. 1,3,4. Now... I would like to have this array look like this: 1,2,3. I Would like the 3 & 4 to simple switch place to one less from their own postion.
I know it's possible, I had a friend do it for me some years ago. How do I do this?
i think you are failing when using splice. splice and slice is different methods for array slice not changes the original array but returns new array with sliced gap
example
var arr:Array = ["Cat","Dog", "Mouse", "Cow"];
trace(arr.slice(1,3));// output : Dog,Mouse
trace(arr.slice(2));//output: Mouse,Cow
trace(arr) //output: Cat,Dog,Mouse,Cow
so when you call arr[3] you are getting Cow but your array didnt change at all
splice modifies your original array
var arr:Array = ["Cat","Dog", "Mouse", "Cow"];
arr.splice(1,1); // output: 0->Cat,1->Mouse,2->Cow
I would like to have this array look like this: 1,2,3
So...just pop() the last element:
myArray:Array = [1, 2, 3, 4];
myArray.pop();
trace(myArray); // Prints: 1,2,3
I Would like the 3 & 4 to simple switch place to one less from their own postion.
Umm...that's exactly what deleting the second element already did...
If the end result you want is that the second element be placed at the end, that is:
Before: [1, 2, 3, 4] --> After [1, 3, 4, 2]
Then you can do that in two steps:
var spliced = myArray.splice(1, 1); // Remove the second element and return it
myArray.push(spliced); // Push it to the end of the array
Technically you could do this in one step, since the splice will happen first:
myArray.push(myArray.splice(1, 1));
I ran your pseudo code ->
Here is the result:
[object Cat],[object Mouse],[object Cow]
There is no index when tracing.. another point, I some code
trace(arr[0] , arr[1], arr[2]);
And I still get
[object Cat],[object Mouse],[object Cow]
The indexes are fine automatically in AS3.
package regression
{
import flash.display.Sprite;
/**
* ...
* #author Arthur Wulf White
*/
public class Check_array_index_test_1 extends Sprite
{
public function Check_array_index_test_1()
{
var arr: Array = new Array();
arr.push(new Cat, new Dog, new Mouse, new Cow);
trace(arr);
arr.splice(1, 1);
trace(arr);
trace(arr[0] , arr[1], arr[2]);
}
}
}
class Cat { }
class Dog { }
class Mouse { }
class Cow {}
Related
lets say I'm making a simple dnd dice roller (cause I am), I get results and I turn it into an array.
Now I want to print the results of the array into a textView that would say:
randNumResultsDisplay.text = "Rolled " then it would spit out all results in the array, in order that they were put in.
I'm not entirely sure where you are stuck here, but if you want to convert an array into a String, one option is to use the java.utils.Arrays class:
val myArray = arrayOf(1, 2, 3)
val contents = Arrays.toString(myArray)
println(contents) // prints "[1, 2, 3]"
So to inject that in your text view as you suggested:
randNumResultsDisplay.text = "Rolled ${Arrays.toString(yourValuesArray)}"
That being said, you would get it for free if you used List instead of Array (which is very much advised):
randNumResultsDisplay.text = "Rolled $yourList"
Another option as pointed out in the comments is the joinToString method, which works on both arrays and lists and allows you to customize the formatting:
println("Rolled: ${myArray.joinToString()}")
// Rolled 1, 2, 3
println("Rolled: ${myArray.joinToString(prefix = "[", postfix = "]")}")
// Rolled [1, 2, 3]
println("Rolled: ${myArray.joinToString(separator = "|")}")
// Rolled 1|2|3
i have 2 arrays:
"interfaceTitles" with the values "USB ports", "digital inputs", "RS232, ...
"interfaceAmounts" with the values "3", "20", "1", ...
I need a merged Array with combined values. So the new array should have the following values:
"3 USB ports", "20 digital inputs" ...
So its not just concating, its fusionating :D
interfacesAdded = interfaceAmounts && interfaceTitles doesn't work
interfacesAdded = interfaceAmounts + interfaceTitles makes it into an string
"interfacesAdded" is declared as const interfacesAdded: any = ...
what can I do for this, Search function didn't help me, sorry im kinda unexperienced :(
Greetings
The below uses the map function to loop over the interfaceTitles list, and return a new list where the elements are the corresponding elements from the two lists joined by a space.
const result = interfaceTitles.map((_, i) => {
return interfaceAmounts[i] + " " + interfaceTitles[i];
});
Hope this is what you are looking for.
I think you could add the language you are using to help better answer,
the logic will be the same in different language, i'm doing it in js.
Admitting the string you want to concat are in the same position of the 2 arrays:
const array1 = [1, 4, 9, 16];
const array2 = ['a','b','c','d'];
// pass a function to map
// care in js we can use the + to concat string
// map will iterate over each element of array1
// x will be the current element of array1
// index will be the index of the current element,
// used to get the corresponding element in array2
const map1 = array1.map((x,index) => x+array2[index]);
console.log(map1);
// expected output: > Array ["1a", "4b", "9c", "16d"]
I have a list of arrays with the same shape, like this:
my_list = [arr_1, arr_2, arr_3, ...]
arr_1.shape
(1988, 1221)
...
Is there a way to multiply every array in my list and get a final array with the same shape?
I've tried this way but it doesn't work:
for i in my_list:
arr_final = np.multiply(my_list[i])
The final array should be the same of every array in the initial list.
arr_final.shape
(1988, 1221)
You can stack them and take product:
mylist = [np.array([1,2]), np.array([2,3]), np.array([1,4])]
np.stack(mylist).prod(0)
Output:
array([ 2, 24])
Below I am trying to fetch the i'th element of the ArraySlice draggignFan. The code builds fine (no warnings) but the program dies at runtime on the line where I try to index the slice like a normal array:
var draggingFan : ArraySlice<Card>?
...
if let draggingFan = draggingFan {
for i in 1 ..< draggingFan.count {
let card = draggingFan[i] // EXECUTION ERROR HERE
...
}
}
According to the docs there is a first and last method (which I use elsewhere with no problem). So how do I index an ArraySlice in Swift? (Note: I am intentionally skipping the 0'th index in the slice -- that's needed elsewhere).
The indices of the ArraySlice still match those of the original array. In your case, you are accessing index 1 which is not in your slice. If you offset the index by draggingFan.startIndex it will work:
if let draggingFan = draggingFan {
for i in 1 ..< draggingFan.count {
let card = draggingFan[draggingFan.startIndex + i]
...
}
}
Alternatively:
if let draggingFan = draggingFan {
for i in draggingFan.startIndex + 1 ..< draggingFan.endIndex {
let card = draggingFan[i]
...
}
}
This will access the values from the second element in the slice to the last element in the slice:
let original = [1,2,3,4,5,6] // Int array to demonstrate
var draggingFan : ArraySlice<Int>?
draggingFan = original[1...4] // create the slice
if let draggingFan = draggingFan {
// so there's no errors just slice the slice and iterate over it
for i in draggingFan[(draggingFan.startIndex+1)..<draggingFan.endIndex] {
print(i, terminator: ", ")
}
}
Output:
3, 4, 5,
The reason you are having this problem is that the slice maintains the original index numbers of the sequence you got it from. Thus, element 1 is not in this slice.
For example, consider this code:
let arr = [1,2,3,4,5,6,7,8,9]
let slice = arr[2...5]
Now what is slice[1]? It isn't 4, even though that is the second thing in the slice. It's 2, because the slice still points into the original array. In other words, slice[1] is out of the slice's range! That is why you're getting a runtime error.
What to do? Well, the actual indexes of the slice are its indices. That is what you want to cycle thru. But... You don't want the first element pointed to by the slice. So you need to advance the startIndex of the range you're going to iterate through. Thus:
if let draggingFan = draggingFan {
var ixs = draggingFan.indices
ixs.startIndex = ixs.startIndex.advancedBy(1)
for i in ixs {
// ... now your code will work ...
}
}
However, in my view, there's no need to index the slice at all, and you shouldn't be doing so. You should cycle through the slice itself, not thru its indexes. You have this:
for i in 1 ..< draggingFan.count
But that is much like saying
for aCard in draggingFan
...except that you want to drop the first element of the slice. Then drop it! Say this:
for aCard in draggingFan.dropFirst()
To see that this will work, try this in a playground:
let arr = [1,2,3,4,5,6,7,8,9]
let slice = arr[2...5]
for anInt in slice.dropFirst() {
print(anInt) // 4, 5, 6
}
As you can see, we are cycling through exactly the desired elements, with no reference to index numbers at all.
To iterate over the elements in the slice:
draggingFan?.forEach({ (element)
...
})
As far as I know, the get a specific element, it needs to be converted back to an array e.g.
let draggingFanArray = Array(draggingFan!)
Here's the playground code I used to toy around with various scenarios:
import Cocoa
var a: Array<Int>?
var b: ArraySlice<Int>?
a = [1, 2, 3, 4, 5, 6, 7]
b = a![3...5]
let count = b!.count
b!.forEach({ (element) in
print("\(element)")
})
let c = Array(b!)
print(c[2])
edit ArraySlice extension though:
extension ArraySlice {
func elementAtIndex(index: Int)->AnyObject?{
return Array(self)[index] as? AnyObject
}
}
If I have an array:
var arr = [1, 2, 3, 4, 5, 6, 7] // [1, 2, 3, 4, 5, 6, 7]
And I take a slice of the array:
let slice = arr[3..<arr.count] // [4, 5, 6, 7]
This slice will have a startIndex of 3, which means that indexing starts at 3 and ends at 6.
Now if I want a slice containing everything but the first element, I can use the dropFirst() method:
let sliceMinusFirst = slice.dropFirst() // [5, 6, 7]
And at this point, sliceMinusFirst has a startIndex of 4, which means my indexes range from 4 to 6.
Now if I wish to iterate over these to do something with the items, I can do the following:
for item in sliceMinusFirst {
print(item)
}
Alternatively, I can do it with forEach:
sliceMinusFirst.forEach { item in
print(item)
}
By using these forms of iteration, the fact that the startIndex is nonzero doesn't even matter, because I don't use the indices directly. And it also doesn't matter that, after taking a slice, I wanted to drop the first item. I was able to do that easily. I could have even done that at the time I wanted to do the iteration:
slice.dropFirst().forEach { item in
print(item)
}
Here I dropped the first item from the original slice, without creating any intermediate variables.
Remember that if you need to actually use the index, you're probably doing something wrong. And if you genuinely do need the index, make sure you understand what's going on.
Also if you want to get back to zero-based indexing once you make a slice, you can create an array from your slice:
let sliceArray = Array(slice) // [4, 5, 6, 7]
sliceArray.startIndex // 0
I want to get a range of objects from an array. Something like this:
var array = [1,3,9,6,3,4,7,4,9]
var newArray = array[1...3] //[3,9,6]
The above would access elements from index 1 to 3.
Also this:
newArray = array[1,5,3] // [3,4,6] would be cool
This would retrieve elements from index 1, 5 and 3 respectively.
That last example can be achieved using PermutationGenerator:
let array = [1,3,9,6,3,4,7,4,9]
let perms = PermutationGenerator(elements: array, indices: [1,5,3])
// perms is now a sequence of the values in array at indices 1, 5 and 3:
for x in perms {
// iterate over x = 3, 4 and 6
}
If you really need an array (just the sequence may be enough for your purposes) you can pass it into Array's init method that takes a sequence:
let newArray = Array(perms)
// newArray is now [3, 4, 6]
For your first example - with arrays, that will work as-is. But it looks from your comments like you're trying it with strings as well. Strings in Swift are not random-access (for reasons relating to unicode). So you can't use integers, they have an String-specific bidirectional index type:
let s = "Hello, I must be going"
if let i = find(s, "I") {
// prints "I must be going"
println(s[i..<s.endIndex])
}
This works :
var n = 4
var newArray = array[0..<n]
In any case in
Slicing Arrays in Swift you'll find a very nice sample of the Python slice using a extension to Arrays in Swift.