Function’s job is to count the number of 1’s in a 3 x 3 subset of a larger array. I translated my C procedure to Go and it works. Then I thought I would get fancy and try a 2 dimensional slice. It doesn’t work.
// Working function translated from C
func count(i int, j int, lx[] string) int {
a := 0
mstart := max(i-1, 0)
nstart := max(j-1, 0)
mstop := min(i+2, height)
nstop := min(j+2, width)
for m:=mstart; m<mstop; m++ {
for n:=nstart; n<nstop; n++ {
if lx[m][n]=='1' { a++ }
}
}
return a
}
// Fancy function that doesn’t work properly
func count(i int, j int, lx[] string) int {
a := 0
mstart := max(i-1, 0)
nstart := max(j-1, 0)
mstop := min(i+1, height-1)
nstop := min(j+1, width-1)
block := lx[mstart:mstop][nstart:nstop]
for m:=range block {
for n, test:=range block[m] {
if test=='1' { a++ }
}
}
return a
}
Just tried it again and it didn’t compile. The compiler complained about ‘n’ not being used. Replaced it with an _ and now it compiles, but it still doesn’t work.
I wrote this to solve the ‘Game of Life’ community puzzle on codingame.com. You can find the whole program there.