For this assignment, you will create the pattern of a chess board that is 8 x 8. Use X and O to represent the squares.
- Create the appropriate nested looping structure to output the characters in an 8 x 8 grid on the screen using Console.Write() or Console.WriteLine() as appropriate.
- Include a decision structure to ensure that alternate rows start with opposite characters as a real chess board alternates the colors among rows.
Simple enough, but my first version stuffed everything inside of Main
, which I don't care for. So, I wrote a second version that nicely separated the concerns. The problem with that, in my eyes at least, is that it now does exactly twice the amount of work as my initial "naive" version. Does the benefit of separating concerns outweigh the performance hit on an already exponential algorithm?
Also, I don't like this snippet (that exists in both versions of the code).
if (row % 2 == 0) { grid[row, col] = (col % 2 == 0) ? dark : light; } else { grid[row, col] = (col % 2 == 0) ? light : dark; }
This differs only in the order of the characters, but I'm too close to it at this point to see a better way to clean up the control logic. Advice on it would be appreciated.
Version 1:
public static void Main()
{
const int gridSize = 8;
const string dark = "x";
const string light = "o";
for (var row = 0; row < gridSize; row++)
{
for (var col = 0; col < gridSize; col++)
{
string output;
if (row % 2 == 0)
{
output = (col % 2 == 0) ? dark : light;
}
else
{
output = (col % 2 == 0) ? light : dark;
}
Console.Write(output);
}
Console.WriteLine();
}
}
Version 2: (ideone here)
public static void Main()
{
var grid = CreateGrid(8, 'o', 'x');
PrintGrid(grid);
}
private static void PrintGrid(char[,] grid)
{
for (var row = 0; row < grid.GetLength(0); row++)
{
for (var col = 0; col < grid.GetLength(0); col++)
{
Console.Write(grid[row, col]);
}
Console.WriteLine();
}
}
private static char[,] CreateGrid(int gridSize, char light, char dark)
{
var grid = new char[gridSize, gridSize];
for (var row = 0; row < gridSize; row++)
{
for (var col = 0; col < gridSize; col++)
{
if (row % 2 == 0)
{
grid[row, col] = (col % 2 == 0) ? dark : light;
}
else
{
grid[row, col] = (col % 2 == 0) ? light : dark;
}
}
}
return grid;
}