Last active
June 19, 2022 03:25
-
-
Save jonurry/08658ed542d2b2574b3095544324de57 to your computer and use it in GitHub Desktop.
2.3 Chess Board (Eloquent JavaScript Solutions)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.