Thursday, November 20, 2008

Dynamic Checkerboard Code

An interesting problem is to draw a dynamic checkerboard or chessboard with the constraints that the height and width of the board are variable along with the fact that the dimension of the individual squares themselves have variable defining their own height and width. The board must be drawn with a simple text output.

The following java solution is proposed


/*
* Create a function that can draw a checkerboard with boardwidth by boardlength where each square is squarewidth by squarelength.
* It is to be drawn with System.out.prints only.
*/
public class DrawCheckerBoard {

public static void drawCheckerBoard(int checkerBoardWidth, int checkerBoardHeight, int squareWidth, int squareHeight)
{
for (int i = 0 ; i < checkerBoardHeight ; i++)
{
for (int j = 0 ; j < squareHeight ; j++)
{
for(int k = 0 ; k < checkerBoardWidth ; k++)
{
//determine character to draw for square
//based on the which checkerboard spot (i and k indices)
String character = "X";
if ((i+k)%2==0)
{
character = "O";
}
for (int l = 0 ; l < squareWidth ; l++)
{
System.out.print(character);
}
}//end of line
System.out.println("");
}
}

}

public static void main(String[] args)
{

System.out.println("4 by 4 board with each square being 2 by 2");
drawCheckerBoard(4,4,2,2);

System.out.println("8 by 8 board with each square being 4 by 4");
drawCheckerBoard(8,8,4,4);

}

}