0

I am trying to create a high dimension array in Golang.
Does anyone know how to do it?

e.g.

  • dims := [3,2,1] as a parameter -> want high_dims_array := make([3][2][1]int, 0)
  • dims := [2] -> want high_dims_array := make([2]int, 0)
  • dims := [3,3] -> want high_dims_array := make([3][3]int, 0)

Where the dims is a variable containing dimensions.

0

2 Answers 2

1

Thanks my friends. I have figured out a way to do this

func initialCube(shape []int) []interface{} {
    // base condition
    if len(shape) <= 1 {
        dim := shape[len(shape)-1]
        retObj := make([]interface{}, dim)
        for i := 0; i < dim; i++ {
            retObj[i] = 0.0
        }
        return retObj
    } else { // recursive
        dim := shape[len(shape)-1]
        retObj := make([]interface{}, dim)
        for i := 0; i < dim; i++ {
            retObj[i] = initialCube(shape[:len(shape)-1])
        }
        return retObj
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

That looks like what dolmen-go/multidim does (it helps to allocate a slice with the required number of elements):

package main

import (
    "fmt"

    "github.com/dolmen-go/multidim"
)

func main() {
    var cube [][][]int
    multidim.Init(&cube, 8, 2, 2, 2)

    fmt.Println(cube)
}

Output:

[[[8 8] [8 8]] [[8 8] [8 8]]]

You can also use a function (still with the same library) to initialize your 3*2 slice:

package main

import (
    "fmt"

    "github.com/dolmen-go/multidim"
)

func main() {
    var a [][]int

    multidim.Init(&a, func(i, j int) int {
        return 2*i + j + 1
    }, 3, 2)

    fmt.Println(a)

    var r [][]string

    multidim.Init(&r, func(i, j int) string {
        return "foobar"[i*3+j : i*3+j+1]
    }, 2, 3)

    fmt.Println(r)
}

Output:

[[1 2] [3 4] [5 6]]
[[f o o] [b a r]]

2 Comments

thanks, but in my question dims is unkonw..which means I can't have var a [][]int at first place . the dimension is a parameter
@EnXie you would need to iterate on your dims, and use make to make a slice of your slices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.