Home > database >  Create a global bidimensional slice with length taken in input
Create a global bidimensional slice with length taken in input

Time:10-23

I need to create a bidimensional slice with a custom length, taken in input. The slice is the field of my minesweeper, so the length will be the dimension of the field. I need the slice to be global, right now I inizialize the slice directly to the costant dimension of the field, but I am implementing the difficulty, so I need the field to be variable.

//my code right now
const dimX int = 16            //X field dimension
const dimY int = 16            //Y field dimension
var bombs int = 40             //number of mines
var number [dimX][dimY]int8    //number contained in the cell, 0 if empty, -1 if mine
var isOpen [dimX][dimY]bool    //if the cell is visible to the user
var isFlagged [dimX][dimY]bool //if the cell is marked as a bomb

Is there a way I can declare the variables and then initialize them in a function, something like this (that way is obv not possible in go):

//what i'd like to do
var dimX, dimY, bombs int
var number [][]int8
    
func main() {
   Scan(&dimX, &dimY, &bombs)
   number = [dimX][dimY]
   ...
}

I tried also something with make, but it gives me an incompatible assign (cannot use make([][]uint8, dimX) (value of type [][]uint8) as [16][16]int8):

func main() {
   Scan(&dimX, &dimY, &bombs)
   number = make([][]uint8, dimX)
   for i := range number {
      number[i] = make([]uint8, dimY)
   }
   ...
}

The only way I found is viable is via the append() function: declare the field to [][] or [0][0] and after the user input run a function that append() x times and y times to the slice

CodePudding user response:

The first snippet of code in the question uses an array of arrays. The length of an array is set at compile time.

Use a slice of slices as in the second snippet of code. The length of a slice is dynamic.

Allocate the slices with make as shown in the third snippet of code.

var dimX, dimY, bombs int
var number [][]int8  // empty [] is a slice.

fmt.Scan(&dimX, &dimY, &bombs)
number = make([][]int8, dimX)
for i := range number {
    number[i] = make([]int8, dimY)
}

Note: The code in the question uses int8 and uint8 when referring to the elements. These are different types. This answer uses int8.

Run the example on the playground.

  •  Tags:  
  • go
  • Related