Create a two-dimensional array at runtime: Difference between revisions

→‎{{header|Go}}: more techniques
(→‎{{header|Go}}: added note on array composition)
(→‎{{header|Go}}: more techniques)
Line 427:
printfn "%d" arr.[0,0]</lang>
=={{header|Go}}==
Arrays in Go are only one dimensional. Code below show the obvious way of composing a 2d array as an array of arrays that can be indexed as a[r][c]. Note though, that it is often more efficient to create a 1d array of size rows*columns and compute indexes yourself, a[r*cols+c] for example.
<lang go>package main
 
Line 455:
a = nil
// memory allocated earlier with make can now be garbage collected.
}</lang>
The technique above alocates each row separately. This might be good if you need extremely large arrays that cannot be allocated in a single piece. It might be bad though, for locality, as there would be no guarantee that the separate allocations would be localized in memory. A technique that maintains locality is this,
<lang go> // allocate composed 2d array
a := make([][]int, row)
e := make([]int, row * col)
for i := range a {
a[i] = e[i*col:(i+1)*col]
}</lang>
Now all rows are allocated with a single allocation. Alternatively, slice e can be used directly without going through slice a. Element r c can be accessed simply as e[r*cols+c] for example, or accessor functions can be defined such as,
<lang go>
func get(r, c int) int {
return e[r*cols+c]
}</lang>
 
1,707

edits