英文:
Iterate a 2D slice of integers diagonally in go
问题
迭代遍历二维整数切片的一种惯用方法是沿着负对角线或正对角线进行遍历。
以下是一个设置了二维网格的示例代码:
package main
import (
"fmt"
)
func main() {
grid := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
// 沿着负对角线遍历
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[i]); j++ {
if i+j == len(grid)-1 {
fmt.Println(grid[i][j])
}
}
}
// 沿着正对角线遍历
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[i]); j++ {
if i == j {
fmt.Println(grid[i][j])
}
}
}
}
你可以在这个链接中查看一个设置了二维网格的 Playground 示例:https://go.dev/play/p/Cpxg4a5HvrD
英文:
What is an idiomatic way to iterate through a 2d slice of integers diagonally. Either the negative or positive diagonals?
Here is a playground with a 2d grid setup.
https://go.dev/play/p/Cpxg4a5HvrD
答案1
得分: 0
如果x == y
,或者在这种情况下,i == j
,那么它就是对角线。
func main() {
size := 4
board := make([][]int, size)
for i := range board {
board[i] = append(board[i], make([]int, size)...)
}
for i, row := range board {
for j := range row {
board[i][j] = rand.Intn(9)
if i == j {
log.Println("对角线:", board[i][j])
}
}
}
for _, row := range board {
fmt.Println(row)
}
}
这将打印:
2021/12/21 01:33:59 对角线: 5
2021/12/21 01:33:59 对角线: 6
2021/12/21 01:33:59 对角线: 5
2021/12/21 01:33:59 对角线: 8
[5 6 2 2]
[4 6 7 8]
[4 6 5 7]
[3 2 4 8]
如果你想要不同的对角线,你可以偏移其中一个轴,例如x == y+1
,或者i == j+1
。
这将打印:
2021/12/21 01:38:07 对角线: 4
2021/12/21 01:38:07 对角线: 6
2021/12/21 01:38:07 对角线: 4
[5 6 2 2]
[4 6 7 8]
[4 6 5 7]
[3 2 4 8]
对于逆对角线,需要使用len(board) - i
,即:
for i, row := range board {
for j := range row {
board[i][j] = rand.Intn(9)
if len(board)-i == j {
log.Println("对角线:", board[i][j])
}
}
}
打印结果为:
2021/12/21 01:57:30 对角线: 8
2021/12/21 01:57:30 对角线: 5
2021/12/21 01:57:30 对角线: 2
[5 6 2 2]
[4 6 7 8]
[4 6 5 7]
[3 2 4 8]
英文:
If x == y
, or in this case, i == j
, then it's the diagonal.
func main() {
size := 4
board := make([][]int, size)
for i := range board {
board[i] = append(board[i], make([]int, size)...)
}
for i, row := range board {
for j := range row {
board[i][j] = rand.Intn(9)
if i == j {
log.Println("diagonal:", board[i][j])
}
}
}
for _, row := range board {
fmt.Println(row)
}
}
That will print
2021/12/21 01:33:59 diagonal: 5
2021/12/21 01:33:59 diagonal: 6
2021/12/21 01:33:59 diagonal: 5
2021/12/21 01:33:59 diagonal: 8
[5 6 2 2]
[4 6 7 8]
[4 6 5 7]
[3 2 4 8]
If you want a different diagonal, you can offset one of the axis, for example x == y+1
, or i == j+1
That will print
2021/12/21 01:38:07 diagonal: 4
2021/12/21 01:38:07 diagonal: 6
2021/12/21 01:38:07 diagonal: 4
[5 6 2 2]
[4 6 7 8]
[4 6 5 7]
[3 2 4 8]
For the inverse diagonals, need to use the len(board) - i
, i.e.
for i, row := range board {
for j := range row {
board[i][j] = rand.Intn(9)
if len(board)-i == j {
log.Println("diagonal:", board[i][j])
}
}
}
Prints
2021/12/21 01:57:30 diagonal: 8
2021/12/21 01:57:30 diagonal: 5
2021/12/21 01:57:30 diagonal: 2
[5 6 2 2]
[4 6 7 8]
[4 6 5 7]
[3 2 4 8]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论