duanqiao3608 2013-03-25 15:02
浏览 44
已采纳

从2d数组中获取lang slice列吗?

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?

  • 写回答

1条回答 默认 最新

  • dongyan8896 2013-03-25 15:33
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试