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.

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路