javaoptimizationdesign-patternsperformance

Compact way to generate checkerboard pattern


I need to generate a checkerboard pattern for a game that I am creating. I have come up with the following (pseudo)code, but feel there must be a more compact way to do this. All suggestions welcome!

for (int i = 1; i < 9; i++){
    for (int j = 1; j < 9; j++){
        if (i % 2 == 1){
            if (j % 2 ==1){
                color = white
            }
            if (j % 2 ==0){
                color = black
            }
        }

        if (i % 2 == 0){
            if (j % 2 ==1){ 
                color = black
            }
            if (j % 2 ==0){
                color = white
            }
        }
        id = (i-1)*8+j
    }//end inner for
}//end outer for

Thanks.


Solution

  • for (int i = 1; i < 9; i++){
        for (int j = 1; j < 9; j++){
            if ( i+j % 2 == 0 ) {
                color = white;
            } else {
                color = black;
            }
        }
    }