More 2D array problems

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
}

Can you describe how the second function does not work? It looks like it won’t compile.

Can you please post a runnable sample using play,golang.org so other can reproduce the problem.

Thank you

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.

This

doesn’t do what you probably imagine it does. It is not a 2D slice operation by any measure.

You can still use slicing to do it, though: http://play.golang.org/p/xRY6ky61rG.

2 Likes

I didn’t really expect it to work, but hey, maybe this is why Go was invented. Never know until you try. Thanks for the clarity.

Can you please post a complete code sample using play.golang.org. Thank you

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.