Reputation: 223
This is from a textbook:
"Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chessboard."
The chessboard looks like this:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
This is my code:
const lineOne = ' # # # # '
const lineTwo = '# # # #'
const chessboard = function() {
console.log(lineOne)
console.log(lineTwo)
console.log(lineOne)
console.log(lineTwo)
console.log(lineOne)
console.log(lineTwo)
console.log(lineOne)
console.log(lineTwo)
}
console.log(chessboard())
While this does output the chessboard, I can tell that this is very inefficient. What is a better way of writing this?
Also the textbook writes, once I have finished writing the program that outputs the chessboard that I should set a binding: size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.
How does one do this? I am told we need a loop inside a loop, but I can't figure it out?
Bear in mind that I am a novice who is learning, so the more you explain the better.
Thank you for your help.
Upvotes: 2
Views: 1494
Reputation: 7368
I think for the beginner this is the most simplest way.
Here are the steps to do this:
Iterate the 2 loops
with size of chessboard
.Outer loop will represent to line
while inner is for column
.
//Here loop iterate (from 0 to < size) means 0 to 7.
Inside inner loop decide that outer loop
index is even
or odd
based on modules.It will decide the start column of line will be space
or block(#)
.
Inside this if and else
just find out inner loop index is even
or odd
and append column ( space
or block(#)
) on basis of it.
var size = 8;
var block = '#';
var space = ' ';
function chessBoard(ChessSize){
for (var i = 0; i < ChessSize; i++) {
var drawLine = '';
for (var y = 0; y < ChessSize; y++){
if (i%2) {
if (y%2) {
drawLine = drawLine + space;
} else {
drawLine = drawLine + block;
}
} else {
if (y%2) {
drawLine = drawLine + block;
} else {
drawLine = drawLine + space;
}
}
}
console.log(drawLine);
}
}
chessBoard(size);
Upvotes: 1
Reputation: 2107
Looping makes your code shorter than it is.
Instead of printing the # # # #
, 8 times you can write it in a loop to let the program print it 8 times by just writing it 1 time.
The if
condition inside the loop will just make the printing alternate so it will make it look like a chess board.
The loop starts at 1 and ends at 8 it is represented by the variable i
. In that case we can distinguish alternate as odd and even numbers.
The if
condition will print lineTwo
if the i
variable is an even number and will print lineOne
if the i
variable is an odd number.
The loop makes it more dynamic since you will just change the end of the loop represented by the variable size
currently at 8
on any number you want.
const lineOne = ' # # # # '
const lineTwo = '# # # #'
const size = 8
const chessboard = function() {
for ( let i = 1; i <= size; i++ ) {
if ( i % 2 === 0 ) {
console.log(lineTwo)
}
else {
console.log(lineOne)
}
}
}
console.log(chessboard())
UPDATED:
const chessboard = (size) => {
for ( let i = 1; i <= size; i++ ) {
var row = ''
for ( let j = 1; j <= size; j++ ) {
i % 2 === 0 ? j % 2 === 0 ? row += '#' : row += ' ' : j % 2 === 0 ? row += ' ' : row += '#'
}
console.log(row + "\n")
}
}
console.log(chessboard(8)) //pass the size of the chessboard here
I remade the chessboard function to accept a variable which holds the size of the chessboard.
I created another loop inside a loop. The loop above is the same just like I did in the first example. But in the second loop, it prints # # # #
in an alternate pattern. Instead of writing the string as a fixed string we made it more dynamic.
Upvotes: -1
Reputation: 29071
function createGrid(size) {
var s = ''
for (var row = 0; row < size; row++) {
var oddRow = row % 2 == 0
if (oddRow) {
s += ' '
}
for (var col = 0; col < size; col++) {
s += ' #';
}
s += '\n'
}
return s
}
console.log(createGrid(8))
console.log()
console.log(createGrid(16))
Upvotes: 0
Reputation: 163272
As your book says, we can do this with a couple of for
loops. We'll have one loop for the line (the y
coordinate), and the column (the x
coordinate).
A for loop is usually used to to execute something a certain number of times. (Technically, it's until a condition is met.) Here's an example:
for (let y = 0; y < 8; y++) {
// Do something
}
In this example, we're initializing the y
variable with the value 0
. As long as y
is less than 8
, we're going to keep running this loop. Also, every loop, we're going to add 1
to the value of y
. (That's what the ++
operator does.)
Now, our "do something" can have another loop inside of it. Putting this together, here's the code you need:
const gridSize = 8;
for (let y = 0; y<gridSize; y++) {
let line = '';
for (let x=0; x<gridSize; x++) {
line += ((x+y)%2) ? ' ' : '#';
}
console.log(line);
}
The outer loop is for lines, and the inner loop is for columns. Now, you'll see this particular line in the inner loop:
line += ((x+y)%2) ? ' ' : '#';
Starting with line +=
...
What this means is that we're going to take the line
variable and concatenate some data to it. That is, since it's a string, the +=
operator takes the existing text data and puts more text on the end of it, re-assigning it back to the line
variable.
Now, (x+y) % 2
...
First, the modulus operator %
. 0 % 2
is 0
, 1 % 2
is 1
, 2 % 2
is 0
, 3 % 2
is 1
, and so on. Basically, divide, and whatever the remainder is is what you get. In this case, we add the row x
and the column y
so that we'll alternate odd/even values for every row. The result of this will either be 1
or 0
.
((x+y)%2) ? ' ' : '#'
...
This is called a ternary. something ? 'truthy' : 'falsy'
means that if something
is true (or truthy, like 1
), then return 'truthy'
. If not, return 'falsy'
. In our case, if the row plus column are odd, return an empty space (which gets concatenated to the line). Otherwise if it's even, return a #
(which also gets concatenated to the line).
After each inner loop, output the line, and start over.
Upvotes: 2
Reputation: 8415
In a chessboard, call each cell A[i, j]
. i
is row index, j
is the column index.
i + j
is even are black.i + j
is odd are white.var numberColumns = 8;
for (var i = 0; i < numberColumns; i++) {
var line = ""
for (var j = 0; j < numberColumns; j++) {
line += ((i + j) % 2 ? "#" : " ");
}
// print the new line
console.log(line + "\n");
}
Upvotes: 0