簡體   English   中英

如何在Golang中創建一個三維數組

[英]How to create a three-dimensional array in Golang

我正在嘗試創建一個包含塊的三維數組(如rubiks-cube)。

我嘗試了很多東西,但我無法讓它發揮作用。

func generateTiles(x int, y int, z int) [][][]*tile{
  var tiles [][][]*tile

  // Something here
  // resulting in a x by y by z array
  // filled with *tile

  return tiles
}

有什么建議么?

您必須自己初始化每個圖層。 示例( 正在播放 ):

tiles = make([][][]*tile, x)

for i := range tiles {
    tiles[i] = make([][]*tile, y)
    for j := range tiles[i] {
        tiles[i][j] = make([]*tile, z)
    }
}

出於性能原因,我個人會使用一維切片,我將其添加為替代方案:

type Tile struct {
    x, y, z int
}

type Tiles struct {
    t       []*Tile
    w, h, d int
}

func New(w, h, d int) *Tiles {
    return &Tiles{
        t: make([]*Tile, w*h*d),
        w: w,
        h: h,
        d: d,
    }
}

// indexing based on http://stackoverflow.com/a/20266350/145587
func (t *Tiles) At(x, y, z int) *Tile {
    idx := t.h*t.w*z + t.w*y
    return t.t[idx+x]
}

func (t *Tiles) Set(x, y, z int, val *Tile) {
    idx := t.h*t.w*z + t.w*y
    t.t[idx+x] = val
}

func fillTiles(w int, h int, d int) *Tiles {
    tiles := New(w, h, d)

    for x := 0; x < w; x++ {
        for y := 0; y < h; y++ {
            for z := 0; z < d; z++ {
                tiles.Set(x, y, z, &Tile{x, y, z})
            }
        }
    }

    return tiles
}

操場

有一個在GoByExample上創建二維數組的示例: https ://gobyexample.com/arrays。 您應該能夠將其擴展為三維案例。

這就是我想出的。

package main

import (
    "fmt"
)

type Tile struct {
    value int
}

func create3D( x, y, z int) [][][]*Tile {
    result := make([][][]*Tile,x)
    for i := 0 ; i < x ; i++ {
        result[i] = make([][]*Tile,y);
        for j := 0; j < y; j++ {
            result[i][j] = make([]*Tile,z);
            for k := 0 ; k < z; k++ {
                result[i][j][k] = new(Tile)
                result[i][j][k].value = i + j + k;
            }
        }
    }
    return result
}

func main() {
    X := 3
    Y := 4
    Z := 5

    mat := create3D( X , Y , Z);
    for i := 0; i < X; i++ {
        for j := 0 ; j < Y; j++ {
            for k := 0 ; k < Z; k++ {
                fmt.Printf("%d ",mat[i][j][k].value)
            }
            fmt.Println();
        }
        fmt.Println();
    }

}

它的工作方式是這樣的,但對我而言,效率非常低。 多次使用append-operation。 它感覺臃腫,應該可以更簡單的方式。

func generateTiles(x int, y int, z int) [][][]*tile {
    var tiles [][][]*tile

    for i := 0; i < z; i++ {
        var layer [][]*tile
        for j := 0; j < y; j++ {
            var row []*tile
            for k := 0; k < x; k++ {
                var t *tile
                t = &tile{}
                row = append(row, t)
                count++
            }
            layer = append(layer, row)
        }
        tiles = append(tiles, layer)
    }

    return tiles
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM