Home > Enterprise >  Iterate a 2D slice of integers diagonally in go
Iterate a 2D slice of integers diagonally in go

Time:12-21

What is an idiomatic way to iterate through a 2d slice of integers diagonally. Either the negative or positive diagonals?

enter image description here

Here is a playground with a 2d grid setup. https://go.dev/play/p/Cpxg4a5HvrD

CodePudding user response:

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]
  •  Tags:  
  • go
  • Related