Home > Software design >  Reduce or make a function of the code below
Reduce or make a function of the code below

Time:12-31

I want to see if all surrounds of a cell in a 2d array are something , or do something with them.

if (mapmines[rndr][rndc] != 9) {
            mapmines[rndr][rndc] = 9;
            if (mapmines[rndr - 1][rndc - 1] != 9)
                mapmines[rndr - 1][rndc - 1]  ;
            if (mapmines[rndr - 1][rndc] != 9)
                mapmines[rndr - 1][rndc]  ;
            if (mapmines[rndr - 1][rndc   1] != 9)
                mapmines[rndr - 1][rndc   1]  ;
            if (mapmines[rndr][rndc - 1] != 9)
                mapmines[rndr][rndc - 1]  ;
            if (mapmines[rndr][rndc   1] != 9)
                mapmines[rndr][rndc   1]  ;
            if (mapmines[rndr   1][rndc - 1] != 9)
                mapmines[rndr   1][rndc - 1]  ;
            if (mapmines[rndr   1][rndc] != 9)
                mapmines[rndr   1][rndc]  ;
            if (mapmines[rndr   1][rndc   1] != 9)
                mapmines[rndr   1][rndc   1]  ;

I have this similir code exept with diferent code between if can i make a function or reduce? i feel like its posible .

CodePudding user response:

if (mapmines[rndr][rndc] != 9)
{
    //  Do all elements in a 3x3 grid:
    for (i = -1; i <= 1;   i)
    for (j = -1; j <= 1;   j)
        if (mapmines[rndr i][rndc j] != 9)
              mapmines[rndr i][rndc j];

    /*  Set the center element afterward so we do not care about the
        loop above modifying it (gives brevity, not efficiency):
    */
    mapmines[rndr][rndc] = 9;
}

That said, preferable code for this may be significantly affected by the context, including how frequently the condition occurs, interactions between the rows and columns, and more. There may be other data structures that are more useful. You would have to give more context.

CodePudding user response:

Well, you could make it a bit smaller with a function like this:

void incrementIfNotNine(int *cell) {
    if(*cell != 9) (*cell)  ;
}

and then call it like this:

incrementIfNotNine(&mapmines[rndr - 1][rndc - 1]);
incrementIfNotNine(&mapmines[rndr - 1][rndc]);
incrementIfNotNine(&mapmines[rndr - 1][rndc   1]);
...

You could also use loops, but for a 3x3 grid, it's hardly worth it.

  •  Tags:  
  • c
  • Related