英文:
dynamic array dimension in golang
问题
我正在尝试在Golang中创建一个高维数组。有人知道如何做吗?
例如:
dims := [3,2,1]
作为参数 -> 希望high_dims_array := make([3][2][1]int, 0)
dims := [2]
-> 希望high_dims_array := make([2]int, 0)
dims := [3,3]
-> 希望high_dims_array := make([3][3]int, 0)
其中 dims
是包含维度的变量。
英文:
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 -> wanthigh_dims_array := make([3][2][1]int, 0)
dims := [2]
-> wanthigh_dims_array := make([2]int, 0)
dims := [3,3]
-> wanthigh_dims_array := make([3][3]int, 0)
Where the dims
is a variable containing dimensions.
答案1
得分: 1
谢谢我的朋友们。我已经找到了一种方法来做这个。
func initialCube(shape []int) []interface{} {
// 基本条件
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 { // 递归
dim := shape[len(shape)-1]
retObj := make([]interface{}, dim)
for i := 0; i < dim; i++ {
retObj[i] = initialCube(shape[:len(shape)-1])
}
return retObj
}
}
英文:
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
}
}
答案2
得分: 0
这看起来像是dolmen-go/multidim
所做的事情(它帮助分配具有所需元素数量的切片):
package main
import (
"fmt"
"github.com/dolmen-go/multidim"
)
func main() {
var cube [][][]int
multidim.Init(&cube, 8, 2, 2, 2)
fmt.Println(cube)
}
输出:
[[[8 8] [8 8]] [[8 8] [8 8]]]
你还可以使用一个函数(仍然使用相同的库)来初始化你的3*2切片:
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)
}
输出:
[[1 2] [3 4] [5 6]]
[[f o o] [b a r]]
英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论