I'm trying to write console minesweeper, but cant figure out how to iterate over 2d array, and count amount of "-1" around each of element. My array looks like
[0 0 0 0 0]
[0 0 -1 0 0]
[0 0 0 0 0]
[0 0 0 -1 -1]
[0 0 0 -1 -1]
Where "-1" that is mine. I've tried to simply iterate over it with code
for i := 0; i < row; i++ {
numb := 0
for j := 0; j < col; j++ {
if ary[i-1][j-1] == -1 {
numb ++ }
}
if ary[i-1][j] == 1 {
numb ++ }
//rest of code omitted
}
But that resulted in huge amout of code, which is hard to read and understand. Is there more flexible way, to check all elements around current
in for-iterator
, so in result it would look like
[0 1 1 1 0]
[0 1 -1 1 0]
[0 1 2 2 1]
[0 0 1 -1 -1]
[0 0 1 -1 -1]
for i := 0; i < row; i++ {
for j := 0; j < col; j++ {
if ary[i][j] == -1 {
for k := max(0, i - 1); k <= min(row - 1, i + 1); k++ {
for l := max(0, j - 1); l <= min(col - 1, j + 1); l++ {
if ary[k][l] != -1 {
ary[k][l] ++
}
}
}
}
}
}
The first two outer loops go through the array. If the observed number is -1
then it increases all surrounding cells unless there is a mine on that field. To avoid the checks if ary[k][l]
is not outside of bounds the bounds are calculated before by using the trick with min / max to ensure that k
and l
are not outside of bounds. E.g. max(0, i-1)
will always return i-1
unless i-1
is smaller than 0
, then it returns 0
.