Store value in an array - arrays

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

Related

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

Runtime Arrays using Create

Say i have
ArrayOfTXSDecimal = array of TXSDecimal;
Then during runtime i do
Ids := ArrayOfTXSDecimal.create(14450);
What did i just create? an array(ids) with 14450 indexs or just index 14450
You are creating a dynamic array with one element whose value is 14450. You are doing the equivalent of this:
SetLength(Ids, 1);
Ids[0] := 14450;
This Create() syntax for dynamic arrays is documented on Embarcadero's DocWiki:
An alternative method of allocating memory for dynamic arrays is to invoke the array constructor:
type
TMyFlexibleArray = array of Integer;
begin
MyFlexibleArray := TMyFlexibleArray.Create(1, 2, 3 {...});
end;
which allocates memory for three elements and assigns each element the given value.

swift: difference between an 2d array and a dictionary

I kinda get confused between the two. I know a dictionary is initialized like:
var Dictionary=[Int:Int]
and is like [1:100,2:150] or [1:"cat",2:"dog"].
But I'm kinda of confused about 2d arrays. I think it is initialized like:
var Arr=[Int[Int]]()
and looks like [[1,4],[5,3]] and It should have an x and y coordinate.
I was wondering if the two are interchangeable and which would work best when making this grid? And if I wanted to store information at coordinate [2,1]=6 which should I use?
[0,1,0,0]
[0,1,1,0]
[1,0,0,1]
Don't get confused by the fact that both arrays and dictionaries use [ ] symbols for their literals. The two are completely different. a dictionary is used when you have a set of keys and each key has an associated value. A 2d array is essentially a matrix of values.
For your little matrix you want a 2d array. You can create and initialize a 2d array like this:
var matrix : [[Int]] = Array(repeating: Array(repeating: 0, count: 10), count: 10)
This would create a 10x10 matrix filled with zeros. To set a value you can do:
matrix[x][y] = 6
as long as x is 0 to rows - 1 and y is 0 to columns - 1.
Or read a value like:
let value = matrix[x][y]

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.

IndexOf() not working

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

Resources