java – Compact way to generate checkerboard pattern

java – Compact way to generate checkerboard pattern

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

I think if you swap colours after each time you draw something, that should accomplish this.
eg.

Start with black
Outer loop i
   Inner loop j
      Print colour square at position i,j
      Swap colours

Should then go, for an odd numbered board
eg.
3×3

bwb
wbw
bwb

java – Compact way to generate checkerboard pattern

I would use an enum with a successor method. Then you can initialise as follows:

  • The colour of position(col = 0, row = 0) is Colour.Black or Colour.White depending on where you define your origin to be.
  • The colour of position(col = 0, row = n) is the successor of position(col = 0, row = n-1).
  • In each row the colour of position(col = m, row = n) is the successor of position(col = m-1, row = n).

Here is the Colour enum:

public enum Colour {
    BLACK, WHITE;
    public Colour successor() {
        // Bulky general implementation.
        //return values()[(ordinal() + 1) % values().length];

        // Simpler version for our binary case.
        return equals( BLACK ) ? WHITE : BLACK;
    } 
}

Leave a Reply

Your email address will not be published.