How to create an n-dimensional array in GoLang?
How to create an n-dimensional array in GoLang? For example, as in Python numpy, where you can create an array of zeros with a single function numpy.zeros([n чисел])
2 answers
Create a mass with this construction, specifying the dimensions and type: [2][2][3]int{}
. All values will be initialized to zeros. Example:
package main
import "fmt"
func main() {
sample := [2][2][3]int{}
fmt.Println(sample[0][0][0])
fmt.Println(sample[1][1][1])
fmt.Println(sample[1][1][2])
}
Due to static typing, it is not possible to create an array of indeterminate dimension on the fly. But if you really need to, you can create an abstraction: a one-dimensional array and code to work with it, which will behave like a multidimensional one. an array of a given dimension, converting multidimensional indexes to one-dimensional ones. For a two-dimensional array, the formula next: matrix[ i ][ j ] = array[ i*w + j ]
, where w
is the width of the matrix, i
is the vertical index, j
is the horizontal index (for more information, see). Similarly, it is possible to implement access by several indexes, including a previously undefined value.
Update. I threw a similar code:
package main
import "fmt"
type MDArray struct {
Dims int
Sizes []int
Weights []int
Data []int
}
func CreateMDArray(sizes []int) MDArray {
total := 1
weights := make([]int, len(sizes))
weights[0] = 1
for i, v := range sizes {
total *= v
if i > 0 {
weights[i] = weights[i-1] * sizes[i-1]
}
}
obj := MDArray {
Dims: len(sizes),
Sizes: sizes,
Weights: weights,
Data: make([]int, total),
}
return obj
}
func (obj MDArray) MakeIndex(keys []int) int {
index := 0
for i, v := range obj.Weights {
index += keys[i] * v
}
return index
}
func (obj MDArray) Get(keys []int) int {
return obj.Data[obj.MakeIndex(keys)]
}
func (obj MDArray) Set(keys []int, value int) {
obj.Data[obj.MakeIndex(keys)] = value
}
func main() {
// Создаём объект многомерного массива
array := CreateMDArray([]int{3, 2, 5})
// Поставим значения равным одномерным индексам
for i, _ := range array.Data {
array.Data[i] = i
}
// Итого в массиве 30 элементов, последний будет иметь индекс 29
fmt.Println(array.MakeIndex([]int{2, 1, 4}))
// Поставим ему значение -1
array.Set([]int{2, 1, 4}, -1)
// Отобразим внутренний одномерный массив
fmt.Println(array.Data)
// Получим: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 17 18 19 20 21 22 23 24 25 26 27 28 -1]
}
I'm afraid it won't be possible to dynamically create an N-dimensional array without knowing the number of its sides.
And so, you can use make
if you do not know in advance how many elements are in it:
N := 3
arr := make([]int, N)
fmt.Println(arr)
// [0 0 0]
arr[0] = 999
fmt.Println(arr)
// [999 0 0]
2-dimensional:
N := 3
matrix := make([][]int, N)
for i := range matrix {
matrix[i] = make([]int, N)
}