Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go lang slice columns from 2d array?

I'm curious, how do you create a column slice from a 2d Array?

I have an array for a game board for Tic-Tac-Toe, and I'm trying to create a column slice, but my slices are coming out identical.

/* Just trying to get rows and columns working first */

func() isWin() bool {
  win := make([]char, SIZE*2)
  for i:= range BOARD {
    fmt.Println("Row")
    win[i] = check(BOARD[i][0:SIZE])
    fmt.Println("Column")
    win[i+SIZE] = check(BOARD[0:SIZE][i])
  }
return false
}

func() check(slice []char) (char) {
  fmt.Println(slice)
  return "-"
}

I give it the following input:

[E E E E]
[E E E E]
[X O E E]
[X O E E]

And I get a return of

Row
[X O E E]
Column
[X O E E]

But I want a return of

Row
[X O E E]
Column
[E E X X]

How do I make this slice?

like image 992
Clark Kent Avatar asked Mar 25 '13 15:03

Clark Kent


1 Answers

What you want to do is not possible with the slice syntax. You think that x[i][0:n] will get you all the columns of row i. What it actually does is returning the columns 0 to n from row i.

You have to use a loop to get a column:

func boardColumn(board [][]char, columnIndex int) (column []char) {
    column = make([]char, 0)
    for _, row := range board {
        column = append(column, row[columnIndex])
    }
    return
}

The code you label with 'Row' is actually the code I would have expected to deliver the columns:

win[i] = check(BOARD[0:SIZE][i])

Semantically the slice indices say: take the ith element of all elements from zero to SIZE. But, as already mentioned, Go slices work differently. Try for yourself:

x := [][]int{{1,2,3},{4,5,6}}
fmt.Println(x[0:2]) // [[1,2,3],[4,5,6]]
fmt.Println(x[0:2][0]) // [1,2,3]

As you can see in line two of the example above, x[0:2] returns the full 2d slice. Consequently taking the first element returns the first row of that 2d slice.

like image 108
nemo Avatar answered Oct 10 '22 20:10

nemo