IndexOf() not working - arrays

In ActionScript 3, it seems like indexOf is not working when I try to find something like [int, int].
For example:
var array:Array = new Array();
array.push([5, 6]);
trace(array.indexOf([5, 6])); //-1
I wonder if I'm missing something here.

Arrays, like all non-primitive types in AS3, are checked by reference, not by value. Whenever you create a new instance of an object (like an array), the variable is actually a pointer to a location in memory where the object resides.
For this reason, your code won't work because you're comparing pointers to two different arrays. The language doesn't know (or care) about the contents of the objects, all it's looking to compare are the memory locations (ie the reference) to the two objects.
If we look at your code:
var array:Array = new Array();/
array.push([5, 6]);
trace(array.indexOf([5, 6])); //-1
You are actually declaring three different arrays, each with its own location in memory. Firs you create the array var, onto this you push a new array, and in this you then try to search for a new array (in indexOf([5, 6]) you are declaring a new array in-line). For this reason the search returns false, because the references do not match - even if the contents of the arrays do.
var array:Array = new Array();
var subArray:Array = [5, 6];
array.push(subArray);
trace(array.indexOf(subArray)); // 0
...this works because the reference to the array matches.
Primitive types - Numeric, Boolean, String, are compared by value eg
var a:int = 10; var b:int = 10; trace(a == b);//True
where reference types are not:
var a:Array = [5]; var b:Array = [5]; trace(a == b);//False
It would be time-consuming for the player to compare all properties of two different objects before declaring them 'equal' or not (as most complex data types do not have a distinct 'value' in the same way that a number does), so for anything non-primitive, lookups and comparisons are done by reference.
Hope this helps.

Everytime you write [5, 6] you are creating a new instance of [int, int]. When doing indexOf() and comparing objects, it only checks if that particular instance exists (by checking for a reference to the object) in the array, not another instance with the same values. You could change your code as follows for it it work as expected:
var arr0:Array = [5, 6];
var array:Array = new Array();
array.push(arr0);
trace(array.indexOf(arr0)); //should print 0 now instead of -1

Related

Typescript array.splice() function weird behavior [duplicate]

In a Mozilla developer translated Korean lang says 'slice method' returns a new array copied shallowly.
so I tested my code.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
var t = animals.slice(2,4);
console.log(t);
t[0] = 'aaa';
console.log(t);
console.log(animals);
but, If slice method returns shallow array, the animals array should be changed with ['ant', 'bison', 'aaa', 'duck', 'elephant'].
Why is it shallow copy?
slice does not alter the original array.
It returns a shallow copy of elements from the original array.
Elements of the original array are copied into the returned array as follows:
For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array.
If a new element is added to either array, the other array is not affected.(source)
In your case the the array consists of strings which on slice would return new strings copied to the array thus is a shallow copy.
In order to avoid this use the object form of array.
strings are primitive types in JavaScript, so you will get a new array with new strings inside.
Your test array should be an array of objects:
var animals = [{name: 'ant'}, {name: 'bison'}, {name: 'camel'}, {name: 'duck'}, {name: 'elephant'}];
var t = animals.slice(2,4);
console.log(t);
t[0].name = 'aaa';
console.log(t);
console.log(animals);
The slice method doesn't change the original array or string. It only cuts a portion of the original string or array and returns it as a copy.
For more understanding of it, kindly check this video below:
https://youtu.be/mUH8hPQfMbg [Slice method made easy for absolute beginners]
May be you are looking for this. Try this!
let animals = ['ant', 'bison', 'camel', [1, 2]];
let t = animals.slice();
t[0] = 'aaa'; // string (primitive datatype)
t[t.length-1][0] = 0; // array (object)
console.log(t);
console.log(animals);
In case of a shallow copy-
Objects will reflect change in the original place from where they were shallowly copied because they are stored as references (to their address in the Heap).
Primitive data types will NOT reflect change in the original place because they are directly stored in the callstack (in Execution Contexts).

How to use contains method on a 2D array in scala

I have a 2d array and I want to check whether an array exists inside the 2d array.
I have tried:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.contains(Array(4, 3))
println(contain)
This should print true but it doesn't work.
Method contains doesn't work because it uses equals to determine equality and for arrays equals is using reference equality, so it will return true only for two references pointing the same object.
You could use find + sameElements:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.find(_.sameElements(Array(4, 3))).isDefined
println(contain)
Consider using ArrayBuffer instead of Array, if you need mutable collection, like so
val arr = ArrayBuffer(ArrayBuffer(2,1), ArrayBuffer(4,3))
val contain = arr.contains(ArrayBuffer(4, 3))
println(contain)
which outputs
true
Also consider question What is the difference between ArrayBuffer and Array
A more elegant solution would be the following
val array = Array(Array(2,1), Array(4,3))
val result = array.exists(_.sameElements(Array(4, 3)))
println(result)
Output
true

Store value in an array

I am fairly new to Go. I have coded in JavaScript where I could do this:
var x = [];
x[0] = 1;
This would work fine. But in Go, I am trying to implement the same thing with Go syntax. But that doesn't help. I need to have a array with unspecified index number.
I did this:
var x []string
x[0] = "name"
How do I accomplish that?
When you type:
var x []string
You create a slice, which is similar to an array in Javascript. But unlike Javascript, a slice has a set length and capacity. In this case, you get a nil slice which has the length and capacity of 0.
A few examples of how you can do it:
x := []string{"name"} // Creates a slice with length 1
y := make([]string, 10) // Creates a slice with length 10
y[0] = "name" // Set the first index to "name". The remaining 9 will be ""
var z []string // Create an empty nil slice
z = append(z, "name") // Appends "name" to the slice, creating a new slice if required
More indepth reading about slices:
Go slices usage and internals
In JavaScript arrays are dynamic in the sense that if you set the element of an array using an index which is greater than or equal to its length (current number of elements), the array will be automatically extended to have the required size to set the element (so the index you use will become the array's new length).
Arrays and slices in Go are not that dynamic. When setting elements of an array or slice, you use an index expression to designate the element you want to set. In Go you can only use index values that are in range, which means the index value must be 0 <= index < length.
In your code:
var x []string
x[0] = "name"
The first line declares a variable named x of type []string. This is a slice, and its value will be nil (the zero value of all slice types, because you did not provide an initialization value). It will have a length of 0, so the index value 0 is out of range as it is not less that the length.
If you know the length in advance, create your array or slice with that, e.g.:
var arr [3]string // An array with length of 3
var sli = make([]string, 3) // A slice with length of 3
After the above declarations, you can refer to (read or write) values at indicies 0, 1, and 2.
You may also use a composite literal to create and initialize the array or slice in one step, e.g.
var arr = [3]string{"one", "two", "three"} // Array
var sli = []string{"one", "two", "three"} // Slice
You can also use the builtin append() function to add a new element to the end of a slice. The append() function allocates a new, bigger array/slice under the hood if needed. You also need to assign the return value of append():
var x []string
x = append(x, "name")
If you want dynamic "arrays" similar to arrays of JavaScript, the map is a similar construct:
var x = map[int]string{}
x[0] = "name"
(But a map also needs initialization, in the above example I used a composite literal, but we could have also written var x = make(map[int]string).)
You may assign values to keys without having to declare the intent in prior. But know that maps are not slices or arrays, maps typically not hold values for contiguous ranges of index keys (but may do so), and maps do not maintain key or insertion order. See Why can't Go iterate maps in insertion order? for details.
Must read blog post about arrays and slices: Go Slices: usage and internals
Recommended questions / answers for a better understanding:
Why have arrays in Go?
How do I initialize an array without using a for loop in Go?
How do I find the size of the array in go
Keyed items in golang array initialization
Are golang slices pass by value?
Can you please use var x [length]string; (where length is size of the array you want) instead of var x []string; ?
In Go defining a variable like var x=[]int creates a slice of type integer. Slices are dynamic and when you want to add an integer to the slice, you have to append it like x = append(x, 1) (or x = append(x, 2, 3, 4) for multiple).
As srxf mentioned, have you done the Go tour? There is a page about slices.
I found out that the way to do it is through a dynamic array. Like this
type mytype struct {
a string
}
func main() {
a := []mytype{mytype{"name1"}}
a = append(a, mytype{"name 2"})
fmt.Println(a);
}
golang playground link: https://play.golang.org/p/owPHdQ6Y6e

Using arrays in Swift

Just started using Swift and I'm getting pissed at a few elements. First is that most standard stuff are structs rather than objects, which means they're passed in as values rather than pointers as I'm used to. The other thing is that using the optional element system is really annoying.
If I am trying to declare an array without putting anything in it, I declare it like this:
var theArray : [Int]
In order to put anything in it, I would declare it like this:
var theArray : [Int]?
Then add objects as follows:
theArray[someIndex] = someInt
//or
theArray.append(someInt)
However, I get an error. In Java, I could have just initialized an array with a length, which would have given me an a fixed-size array with all 0's.
The problem, summarized in a sentence, is adding elements to Swift arrays that have been initialized without values. How do you do this?
In order to initialize an empty array use:
var theArray : [Int] = []
then add elements by using append method. What you currently did is that you just declared it in the first case non optional and in the second case as an optional variable typed as int array without initializing it.
If you want the array to contain Int types, of course there are many ways to declare that, based on implicit or explicit type inference. These are all valid declarations of an array containing Int types
var array1 = [Int]()
var array2: [Int] = []
var array3 = Array<Int>()
var array4: Array<Int> = []
If you want an array of a certain size, with the values initialized to a certain value you can use, in this example you'll get an Array<Int> with 5 elements, all initialised to 0
var array = Array(count: 5, repeatedValue: Int(0))
Here you go:
var theArray = Array(count:[the length you want], repeatedValue:Int(0))
This will replicate the Java behaviour.

AS3 manipulation of multidimensional array

good day :)
Why is it that when i edit the hold:Array, the array:Array also gets editted?
To give an example:
function func(2, 2) { //x, y COORDINATE
var hold = array[2]; //GET COLUMN OF ARRAY
hold[2] = 2; //SET hold[x] to 2
trace(array[2][2]) //SAME AS hold[x] *but i didn't change array[x]'s value!*
}
STEP BY STEP analysis
array[] looks like this (for example):
1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1
Thus, var hold = array[y]: (where y=2)
1,1,1,1
and hold[x] = 2 (where x=2)
1,2,1,1
Now, tracing array[y][x] (where y=2, x=2)
1,2,1,1
But array[2][2] should be 1,1,1,1, because we didn't edit it's value!
Question
Why does array[] get edited when i only edited hold[]
This is because arrays (typeof will give Object) are passed by reference. To copy its values you need to clone an array in ActionScript.
Here's an explanation of this for ActionScript 2.0 (which also applies to ActionScript 3.0 but I couldn't find the version of this article for the latter).
Yes, arrays are stored against variables as a reference. This means that when you create your array array and then store it in hold to create a 2D array, you're simply storing a reference to array within hold.
For example, you would expect that if you stored a Sprite within an array and then edited that Sprite's values, that you would see those changes from anywhere else you've referenced the Sprite. This is the same for arrays.
var array:Array = [];
var another:Array = [];
var sprite:Sprite = new Sprite();
array.push(sprite);
another.push(sprite);
array[0].x = 10;
trace(another[0].x); // Also 10.
If you don't want this behaviour, you can use .slice() or .concat() to make a shallow clone of an array:
array.push(hold.slice()); // or
array.push(hold.concat());

Resources