Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active June 19, 2022 03:25
Show Gist options
  • Save jonurry/08658ed542d2b2574b3095544324de57 to your computer and use it in GitHub Desktop.
Save jonurry/08658ed542d2b2574b3095544324de57 to your computer and use it in GitHub Desktop.
2.3 Chess Board (Eloquent JavaScript Solutions)
var gridSize = Number(prompt("Enter size of grid", "8"));
var totalSize = (gridSize * gridSize) + gridSize;
var grid = "";
for (i = 0; i < totalSize; i++) {
if (i % (gridSize + 1) == 0)
grid += "\n";
else if (i % 2 == 0)
grid += "#";
else
grid += " ";
}
console.log(grid);
@jonurry
Copy link
Author

jonurry commented Feb 16, 2018

Hints

The string can be built by starting with an empty one ("") and repeatedly adding characters. A newline character is written "\n".

To work with two dimensions, you will need a loop inside of a loop. Put curly braces around the bodies of both loops to make it easy to see where they start and end. Try to properly indent these bodies. The order of the loops must follow the order in which we build up the string (line by line, left to right, top to bottom). So the outer loop handles the lines and the inner loop handles the characters on a line.

You’ll need two bindings to track your progress. To know whether to put a space or a hash sign at a given position, you could test whether the sum of the two counters is even (% 2).

Terminating a line by adding a newline character must happen after the line has been built up, so do this after the inner loop but inside of the outer loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment