Initialize 2d dynamic array in Go

I am trying to create a 2d array in Go:

board := make([][]string, m) for i := range board { board[i] = make([]string, n) } 

However, given the verbosity, I wonder if there is a better or more concise way to deal with this problem (either generate dynamic arrays, or another / idiomatic data structure for processing card games such as data)?


Background:

  • this is for a board game
  • the dimensions of the board are unknown until the user starts to play (so, say, MxN).
  • I want to save an arbitrary character (or one char string) in each cell. In my game, TicTacToe will have an “X” or “O” (or any other character that the user selects).
+7
arrays multidimensional-array go dynamic-arrays
source share
2 answers

What you are building in your code example is not a 2D array, but rather a slice of slices: each of the sub-sections can have a different length with this type, so you have separate distributions for each.

If you want to present a board with a single distribution, one option would be to select a single fragment, and then use simple arithmetic to determine where the elements are. For example:

 board := make([]string, m*n) board[i*m + j] = "abc" // like board[i][j] = "abc" 
+12
source share

The method you described creates a slice of slices that looks like the 2d array you want. I suggest you change the type to uint8, since you will be interested in only 3 states of nothing / first / second player.

This selects each line separately (in your tests you will see at least m + 1 allocs/op ). This is not very pleasant, because there is no guarantee that individual distributions will be localized close to each other.

To save the location, you can do something like this:

 M := make([][]uint8, row) e := make([]uint8, row * col) for i := range M { a[i] = e[i * col:(i + 1) * col] } 

This will end up with only 2 distributions, and the slice slice will maintain data locality. Please note that you can still access your M in the format 2d M[2][6] .

A good video that explains how to do it even faster.

+2
source share

All Articles