Go lang slice columns from 2d array?

I am curious how you create a column slice from a 2d array?

I have an array for the playing field for Tic-Tac-Toe, and I'm trying to create a column slice, but my fragments are output the same.

/* 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 him the following input:

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

And I get a refund

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

But I want to return

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

How to make this fragment?

+5
source share
1 answer

What you want to do is not possible with slice syntax. You think that it x[i][0:n]will give you all the columns of the row i. In fact, this returns the columns 0in nfrom the row i.

You should use a loop to get the 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 call "String" is actually the code that I would expect to deliver columns:

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

: i - SIZE. , , Go -. :

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]

, x[0:2] 2d-. 2d-.

+5

All Articles