Need to create a chessboard with the following rule set:
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.
Passing this string to console.log should show something like this:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Here is the code i wrote for it:
var chessBoardSize = 8;
var chessBoard = " ";
var lineBreakCount = 0;
while (chessBoard.length <= chessBoardSize * chessBoardSize) {
lineBreakCount++;
if (lineBreakCount === chessBoardSize) {
chessBoard += "\n";
lineBreakCount = 0;
}
if (chessBoard.slice(-1) === " ") {
chessBoard = chessBoard + "#";
} else if (chessBoard.slice(-1) === "#") {
chessBoard = chessBoard + " ";
}
}
console.log(chessBoard);
I'm having trouble to get the string on a new line once 8 characters have been used on that line. This is the part of the program i'm trying to figure out:
lineBreakCount++;
if (lineBreakCount === chessBoardSize) {
chessBoard += "\n";
lineBreakCount = 0;
}
When i run the code, i get back this:
# # # #
But, it should be this:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Your logic doesn't handle the fact that the last character maybe a newline character not just '#' or ' '.
This should work:
var chessBoardSize = 8;
var chessBoard = " ";
var lineBreakCount = 0;
var max = chessBoardSize*chessBoardSize;
for(let i = 1; i < max; i++) {
lineBreakCount++;
if (lineBreakCount === chessBoardSize) {
chessBoard += "\n";
lineBreakCount = 0;
}
if (chessBoard[chessBoard.length - 1] === '\n') {
chessBoard += chessBoard[chessBoard.length - 2];
} else if(chessBoard.slice(-1) === " ") {
chessBoard += '#';
} else {
chessBoard = chessBoard + " ";
}
}
console.log(chessBoard);
You're trying to solve a simple problem with complex solution.
The result is a Matrix which means you ( maybe not required ) need nested loops.
Loop through columns.
Loop through a line.
Add checks if-else to choose between #or " ".
We see the position of # is only on a case that achieves this math rule: case%2 === 0.
const chessboard = (size, lineLength) => {
for (let vindex = 0; vindex < size + 1; vindex++) {
let line = String("");
for (let hindex = 0; hindex < lineLength + 1; hindex++) {
vindex % 2 === 0 && ((hindex % 2 === 0 && (line += "#")) || (line += " "))
vindex % 2 != 0 && ((hindex % 2 != 0 && (line += "#")) || (line += " "))
}
console.log(line)
}
}
chessboard(8, 10)
I'm trying to 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 chess board.
Passing this string to console.log should show something like this:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
When you have a program that generates this pattern, define a variable size = 8 and change the program, so that it works for any size, outputting a grid of the given width and height.
var hash = "#";
var space = ' ';
var size = 8;
for (var x = 1; x <= size; x++); {
var line = ' ';
for (var y = 1; y <= size; y++); {
if (x % 2) {
if (y % 2) {
line = line + space;
} else {
line = line + hash;
}
} else {
if (y % 2) {
line = line + hash;
} else {
line = line + space;
}
}
}
console.log(line);
}
I'm having trouble figuring out why this is not working...:(
Remove the semicolons at the end of your loops:
for (var x = 1; x <= size; x++) {
var line = ' ';
for (var y = 1; y <= size; y++) {
With the semicolons, the engine will do the following:
Run the stuff after 'for' inside the brackets - i will be 10 afterwards
stuff inside the curly brackets will be executed once afterwards
If you add a line break it becomes obvious
for (var i = 0; i < 10; i++);
{console.log(i);}
The curly braces are not the body of the for, but a new block.
Make sure you remove ; - s in front of for loops, because of that your for loops are not properly executing logic inside brackets (code will just run once):
Something like this will do what you want:
var size = 8;
for (var y = 0; y < size; y++) {
var line = ' ';
for (var x = 0; x < size; x++) {
line += (y + x + 1) % 2 ? ' ': '#';
}
console.log(line);
}
I'm not sure why my code works the first two lines then says 'undefined' the last few. Its supposed to be a pattern that goes for 8 lines.
var x = console.log(" # # # #");
var y = console.log("# # # # ");
for (var i = 1; i < 9; i++) {
if(i % 2 == 0){
console.log(y);
}
else{
console.log(x);
}
}
You are printing out a console.log.
try
var x = " # # # #";
var y = "# # # # ";
for (var i = 1; i < 9; i++) {
if(i % 2 == 0){
console.log(y);
}
else{
console.log(x);
}
}
or maybe you intended to do the following:
var x = function(){ console.log(" # # # #") };
var y = function(){ console.log("# # # # ")};
for (var i = 1; i < 9; i++) {
if(i % 2 == 0){
y();
}
else{
x();
}
}
Why is your code not working?
when you declare:
var x = console.log(" # # # #"); // <- THE STRING IS BEING PRINTED OUT AT THIS POINT. NOT IN THE FOR LOOP.
console.log is a function which returns undefined. Therefore x is undefined.
Because console.log returns undefined.
Try this:
var x = " # # # #";
var y = "# # # # ";
for (var i = 1; i < 9; i++) {
if(i % 2 == 0){
console.log(y);
}
else{
console.log(x);
}
}
Is that what you're looking for?
var x = " # # # #";
var y = "# # # # ";
for (var i = 1; i < 9; i++) {
if(i % 2 == 0){
console.log(y);
} else{
console.log(x);
}
}
Your code is throwing undefined as you're trying to get the value of console.log();
var x = " # # # #";
Don't put the console.log in the variable declaration.
I am trying to solve the last problem from chapter 2 of Eloquent JavaScript. It is at the very bottom of this page: http://eloquentjavascript.net/02_program_structure.html
(I tried copy pasting but the hashtag symbols keep messing up the formatting).
This is my code that crashes. It seems like it's stuck in an infinite loop or something but I can't see why!
var grid = "";
var bool = true;
var size = 8;
for(var i = 0; i < size; i++) {
if(bool = true) {
for(var i = 0; i < (size/2); i++) {
grid += " #";
}
grid += "\n";
bool = false;
}
else {
for(var i = 0; i < (size/2); i++) {
grid += "# ";
}
grid += "\n";
bool = true;
}
}
console.log(grid);
You're using the assignment operator = instead of comparator ( == or ===) . I.d probably change the name of the variable inside the second cycle for.. It may mess up with the one from the outer for cycle
Two problems:
if(bool = true) should be if(bool == true) (causing the infinite loop)
for(var i = 0; i < (size/2); i++) should be for(var j = 0; j < (size/2); j++) (i is already used in the outer loop)
Suggestions:
Change bool to something like odd_row
If you want to check if a boolean variable is true, you don't need the comparison: if(variable) also works
Try this: https://jsfiddle.net/t3rxx9dk/
var grid = "";
var bool = true;
var size = 8;
for(var i = 0; i < size; i++) {
if(bool == true) {
for(var j = 0; j < (size/2); j++) {
grid += " #";
}
grid += "\n";
bool = false;
}
else {
for(var j = 0; j < (size/2); j++) {
grid += "# ";
}
grid += "\n";
bool = true;
}
}
console.log(grid)
You should use another name for your iterator, you always use "i", that might cause issues
basic issues with your code
var grid = "";
var bool = true;
var size = 8;
for(var i = 0; i < size; i++) {
if(bool = true) {
// ^ -- trouble
for(var i = 0; i < (size/2); i++) {
// ^ another piece of trouble
grid += " #";
}
grid += "\n";
bool = false;
}
else {
for(var i = 0; i < (size/2); i++) {
grid += "# ";
}
grid += "\n";
bool = true;
}
}
console.log(grid);
on a better way to organize the code
var grid = ""
var shiftLine = false;
var size = 8;
for(var i = 0; i < size; i++) {
for(var k = 0; k < (size >> 1); k++) {
grid += shiftLine? " #" : "# ";
}
shiftLine = !shiftLine;
grid += "\n";
}
outputs
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
an exercise
As an exercise for you to review... Here is a way to do this in javascript in a way that takes advantage of Arrays and Strings and demonstrates a few different concepts of functional programming.
var size = 8;
var grid =
Array(size)
.join(
Array((size>>1)+1) // START HERE: create empty array of 1+ size/2
// because we want to delimit it '# ' to get
// size/2 '#'s
.join('# ') // join its elements using "# "
// this gives you a string "# # # # "
.trim() + '\n' // trim off last space and add newline
) // join these lines into an array of size (see Array(size) above)
.trim() // trim off the empty element at the end (due to last new-line)
.split('\n') // split it up into array elements because we need to shift every second line
.map(function(element, index, array) { // for each element (a line of # # # #)
if(index % 2 === 0) // if its index is even
return " " + element; // tack on a leading space
else // otherwise
return element; // leave it alone
})
.join('\n'); // now join everything with a new line
console.log(grid);
new coder here trying to learn JS. I did codecademy already and am working through Eloquent Javascript now. I finally got something together after scratching my head for a very long while... but it doesn't work! I'm not quite sure if I'm approaching this from the right angle but I do know I want to use the loops to track progress through the printing of the # based grid.
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 chess board.
Passing this string to console.log should show something like this:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
My code is below:
var chessBoard = "";
var size = 8;
for (var lineCounter = 1; lineCounter < size; lineCounter++) {
if (lineCounter%2 === 0) { /
/if lineCounter is an even number
for (var charCounter = 1; charCounter < size; charCounter++) {
var evenOdd = (charCounter%2 === 0);
switch (evenOdd) {
case true:
(chessBoard += "#");
break;
case false:
(chessBoard += " ");
break;
}
}
}
else { //if lineCounter is an odd number
for (var charCounter = 1; charCounter < size; charCounter++) {
var evenOdd = (charCounter%2 === 0);
switch (evenOdd) {
case true:
(chessBoard += " ");
break;
case false:
(chessBoard += "#");
break;
}
}
}
chessBoard += "\n";
}
console.log(chessBoard);
The current output of the program is this:
# # # #
# # #
# # # #
# # #
# # # #
# # #
# # # #
Through some iterations, I've already learned a lot, but right now I already see an error - I'm clearly down to a 7x7 grid instead of the 8x8 I wanted to get. I suspect it has to do with me using "<" in my for loops, but not sure if there's a better way to tackle this instead of just adding an extra digit.
It's actually pretty easy you need to make two loops,
one for each row and the other for choosing the element you want to console.log (either ' ' or '#').
check the comments through solution
var size = 8; //this is the variable setting
var board = "";//this is the empty string we're going to add either ' ' , '#' or newline
for (var y = 0; y < size; y++) { /*in the outer loop we add newline to seperate rows*/
for (var x = 0; x < size; x++) {/*every inner loop rappresents a line, and alternatively it's adding either ' ' or '#' to the string that's being populated*/
if ((x + y) % 2 == 0)
board += " ";
else
board += "#";
}
board += "\n";
}
console.log(board);
jsFiddle Demo
I am a fan of chess :) In chess, there is the rule "White on right" which means that the first square of our chess board will be " ". Following that it will alternate every time there is an odd match between row and column.
var board = "";
for(var i = 0; i < 8; i++){
for(var a = 0; a < 8; a++){
board += (a % 2) == (i % 2) ? " " : "#";
}
board += "\n";
}
Viewing the board, it now shows an 8x8 grid
console.log(board);
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Feel free to substitute i for a row number or a for a column number. Or set both to a size :) It will still work. For example, a < 20 will give 20 columns
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
Here's a different approach.
Each row has four instances of either _# or #_ (where the underscore is a space).
Even-numbered rows begin with _# and odd-numbered rows begin with #_:
var chessBoard= '',
size= 8,
c;
for(var i = 0 ; i < size ; i++) {
c= i%2 ? '# ' : ' #';
for(var j = 0 ; j < size/2 ; j++) {
chessBoard+= c;
}
chessBoard+= '\n';
}
console.log(chessBoard);
Here's a version
console.log((new Array(65).join().split("")).map( function(v,i) {
return ( (i/8 >> 0 ) % 2 ? ( i%2 ? " " : "#") : (i%2 ? "#" : " ") ) +
( (i+1) %8 ? "" : "\n" );
}).join(""));
var chessBoard = "";
var size = 8;
for (var lineCounter = 1; lineCounter < size; lineCounter++) {
if (lineCounter%2 === 0) { //if lineCounter is an even number
for (var charCounter = 1; charCounter < size; charCounter++) {
var evenOdd = (charCounter%2 === 0);
switch (evenOdd) {
case true:
chessBoard += "#";
break;
case false:
chessBoard += " ";
break;
}
}
}
else { //if lineCounter is an odd number
for (var charCounter = 1; charCounter < size; charCounter++) {
var evenOdd = (charCounter%2 === 0);
switch (evenOdd) {
case true:
chessBoard += " ";
break;
case false:
chessBoard += "#";
break;
}
}
}
chessBoard += "\n";
}
console.log(chessBoard);
Using only the knowledge provided up to that point in the book Eloquent JavaScript here is my solution:
var board = "";
var size = 8;
// Outer for loop creates a new line** after each cycle of the inner for loop
for (var lineCount = 0; lineCount < size; lineCount++) {
//The nested for loop adds a character to the board variable on a single line proportional to the size variable
for (var spaceCount = 0; spaceCount < size; spaceCount++) {
//This if statement creates the offset lines in the example image by alternating the first character depending on the lineCount
if (lineCount % 2 == 0) {
var black = "#",
white = " ";
} else {
black = " ";
white = "#";
}
if (spaceCount % 2 == 0) {
board += white;
} else {
board += black;
}
}
board += "\n"; //** new line created
}
console.log(board);
here is my version.
Is not as clean and eloquent as the book one but it works!
var size = 8;
var board = " ";
for (var z = 0; z < size; z++) {
for (var y = 1; y < size; y++) {
if (board[y-1]===" ")
board += "#";
else
board += " ";
}
board += "\n";
console.log(board);
if (board[0]===" ")
board = "#";
else
board = " ";
}
var size = 8;
var block = '#';
var space = ' ';
for (var i = 1; i <= size; i++) {
var line = '';
for (var y = 1; y <= size; y++){
if (i%2) {
if (y%2) {
line = line + space;
} else {
line = line + block;
}
} else {
if (y%2) {
line = line + block;
} else {
line = line + space;
}
}
}
console.log(line);
}
That's my solution:
var size=8, line="", c="";
for (i=0;i<size;i+=1){
i%2==0?c=" ":c="#";
for(n=0;n<size;n+=1){
c==" "?c="#":c=" ";
line+=c;
}
console.log(line);
line=""
}
just wanted to add mine :)
var times = 8; //set the times you want to run the loop
var result = '';//result is the chessboard.
for(var i = 0; i < times; i++){ //run the loop starting at zero and going up.
for(var x = 0; x <= 4; x++){ //run a second loop to run each line of the chessboard.
if(i % 2 === 0){ //check if i(current index of the loop) is divisible by 0, and concatenate '# ' to result
result += '# ';
}else{ //if not divisible by 0 then concatenate ' #'
result += ' #';
}
}
result = result + '\n' //add a line brake to at the end of every index
}
console.log(result); //result should now print the chessboard.
So me and some coding buddies were going back and forth optimizing this function for fun and education.
I didn't see our winning solution up here so why not throw it up?
function board(size) {
// determine if we're dealing with an odd board size
var odd=size%2,
// get size-1 if odd, so we can simplify things
s=odd?size-1:size,
// our first row base
r1 = " #",
// our first row
row1 = r1,
// our second row base
r2 = "# ",
// our second row
row2 = r2,
// total size of board, including newlines
total = (size*size)+size,
// our output
out = "",
// our board base
o;
// if size was 1, then it would be odd and s = 0
// in that case return first row, first character
// just a single white space
if(!s) {
return r1[0];
}
// next we build our rows with 2 loops
// this first loop doubles each row until we're within 2*n of total length
// we'd want to skip this step for small values of size
for(n=2;2*n<s;n*=2) {
row1+=row1;
row2+=row2;
}
// this second loop adds our bases until we have the size length
while(row1.length<s) {
row1+=r1;
row2+=r2;
}
// if our size is odd, then a row ends with the same character it begins with
if(odd) {
row1+=r1[0];
row2+=r2[0];
}
// add our newlines to complete our rows
row1+="\n";
row2+="\n";
// we do the same thing to build the board, 2 loops
// start with our base of the 2 rows we just built
out = o = row1+row2;
// double up the rows until we're within 2*n rows of a full board
// again, we'd want to skip this step for small values of size
for(n=2;2*n<s;n*=2) {
out+=out;
}
// add the base until we're complete or 1 row off (if odd)
while(out.length+size+1<total) {
out+=o;
}
// if odd add the first row as final row
if(odd) {
out+=row1;
}
// return the completed chessboard string
return out;
}
// function call with size, returns our chessboard string
console.log(board(8));
If you remove the for(n=2;2*n<s;n*=2) loops then it'll run faster for generating smaller boards but keeping them in makes it much more efficient for larger boards. Ideally you could calculate and specify a threshold and skip the for loops when size<threshold.
this might be late but there are answers on the from the page itself see: http://eloquentjavascript.net/code/
manipulate for loop/formulas for understanding like
var size = 8;
var board = "";
for (var y = 0; y < size; y++) {
for (var x = 0; x < 1; x++) {
if ((x + y) % 2 == 0)
board += (x+y)+"%";
else
board += (x+y)+"#";
}
board += "\n";
}
console.log(board);
I tried mine with while loops and a basic understanding of the books solution.
var board = ""
var size = 8
var x = 0
var y = 0
while (x < size) //restricts number of rows "size" times
{
while (y < size) //changes value of board to board+= # or " " a combined "size" times restricting columns to "size"
{
if ((x+y) % 2 == 0) //adding x+y ensures each row begins with altering #/_
board += " "; //increases value of board by _
else
board += "#"; //increases value of board by _
y++; // increases from 0-8 allowing loop to execute 8 times.
}
board += "\n";
x++; // increases from 0-8 allowing loop to execute 8 times.
y = 0; //resets vaule of y to 0 to allow inner loop to repeate
}
console.log(board) // board prints as a repeating string of #_ using line breaks to create new rows
var sizeX = 8,
sizeY = 8;
var emty = " #",
grid = "# ";
for (x = 0; x < sizeX; x++) {
if (x % 2) {
console.log(emty.repeat(sizeY))
} else {
console.log(grid.repeat(sizeY))
}
}
Here it goes an alternative answer using ternary operator (my first contribution :D):
var size = 8; //this is the variable setting
var board = "";//this is the empty string we're going to add either ' ' , '#' or newline
for (var i = 0; i < size; i++) { /*in the outer loop we add newline to separate rows*/
for (var j = 0; j < size; j++) {/*every inner loop represents a column, and alternatively it's adding either ' ' or '#' to the string that's being populated*/
((i+j%2==0 ? board+=" ": board+="#") /*Here you can see the ternary operator. The syntax = condition ? true: false */
}
board+="\n";
};
console.log(board);
I did the following... It's not very eloquent but it worked for the scenerio.
var hash = ' # #';
var rehash = '# # ';
for( var i = 1; i<9; i++){
if( i%2 ==0){
console.log(rehash+ rehash);}
else{
console.log(hash + hash);}
}
I used two independent FOR loops and it worked. Hopefully independent FOR loops makes it readable. Size of the board can be modified and it reflects accordingly.
size = 8
oddline = ""
evenline = ""
/*First for loop is for creating the first and second lines*/
for (i=0;i<size/2;i++)
{
oddline = oddline + "#" + " "
evenline = evenline + " " + "#"
}
/* This for loop is for printing the first and second lines repeatedly */
for (j=0;j<size/2;j++)
{
console.log(oddline)
console.log(evenline)
}
Not the most elegant solution I'm sure but it works.
let chessBoard = "";
const boardSize = 8;
for (let yAxis = 0; yAxis < boardSize; yAxis++) {
for (let xAxis = 0; xAxis < (boardSize / 2); xAxis++) {
if (yAxis % 2 === 0) {
chessBoard += " ";
chessBoard += "#";
}
else {
chessBoard += "#";
chessBoard += " ";
}
}
chessBoard += "\n";
}
console.log(chessBoard)
I created a solution using the String.repeat method that I think is much cleaner than many of the solutions here:
var size = 8;
var grid = "";
for (i = 1; i <= size; i++) {
if (i%2 == 0)
grid += "# ".repeat(size/2) + "\n";
else
grid += " #".repeat(size/2) + "\n";
}
console.log(grid);
function PrintChessBoard(x,y){
var newHashString = CreateHashString(8);
var charArray = newHashString.split('');
//var tempArry =[];
for(var i = 1 ; i<=y ;i++)
{
if(i % 2 ==0){
for(var j=0 ; j<x; j=j+2){
charArray[j+1] = ' ';
}
}
else{
for(var k=0 ; k<x ; k += 2){
charArray[k] = ' ';
}
}
var HashString = ConcatArrayToString(charArray)
//reset array
charArray = newHashString.split('');
console.log(HashString);
}
}
function CreateHashString(x){
var hashString = '';
while(x>0){
hashString +='X';
x--;
}
return hashString;
}
function ConcatArrayToString(arr){
var nS ='';
for(var i = 0 ; i<arr.length ;i++){
nS +=arr[i];
}
return nS;
}
PrintChessBoard(8,8);
In case someone wonders, there is a way to do this with only one loop:
var chess="";
var size=8;
var k=0, l=1;
//k is to check even for now
//l is for odd for now
var tmp;
var isEven=false;
//we check if chess is Even (if not isEven stays false)
if(size%2==0)
isEven=true;
//sqSize tells us how many chess squares are there
sqSize= size*size;
for(var i=1; i<sqSize+1;i++){
/*
At the beginning of loop we check if the i is even
When we have even ches e.g. 8x8 we need to swap condition
every line (is i even? ----> is i odd? ---->etc.)
*/
if (i%2==k)
chess+=" ";
else
chess+="#";
if (i%size==0){
chess+="\n";
//Adding new line every "size" number.
/*
Here the the swap happens
Earlier, we checked if the size is odd or even.
Now we use this knowledge.
k is condition value. we swap 0 to 1, so we will
be checking different condition in the next loop passing.
*/
if(isEven==true){
tmp=k;
k=l;
l=tmp;
}
}
}
console.log(chess);
The official solution uses the newline character /n which I understand. By nesting the two for loops inside of each other, you can build up the whole chess board in one line. Sure.
But if I want to build an oddRow (starting with # and repeating across the width) and an evenRow (starting with _ and repeating across the width) separately, then print each row sequentially with a new console.log function here's how I did it.
The reason I'm taking this approach was because printing multiple console.log lines was just used in exercise 2.1 "looping a triangle" of the same book. It appears more logical to me, and this works.
var size = 8;
var evenRow = "";
var oddRow = "";
for (var j = 0; j < size; j++) {
evenRow += " #";
oddRow += "# ";
}
for (var i = 0; i < size; i++) {
if (i % 2 == 0) //even
console.log(evenRow);
else //odd
console.log(oddRow);
}
Here is another simplified version of this:
function chessBoard(symbol, gridSize) {
gridSize = gridSize || 8;
symbol=symbol || "#";
let pattern = "";
for (let i = 0; i < gridSize/2; i++)
pattern += symbol + " ";//Forming the pattern
for (let i = 0; i < gridSize; i++) {
if (i % 2 === 0) {
console.log(pattern);
}
else {
console.log(" " + pattern) //For even rows adding the space in front
}
}
}
chessBoard('#',8);
let num = prompt("choose area of board"); // gets input to determine board size.
rowString = "";
for (let height = 0; height < num; height++){ // sets board height
for(let width = 0; width < num; width++){ // sets board width
if ((height+width) % 2 == 0){ // alternates chars by row & height position
rowString += "# ";
}
else{
rowString += " ";
}
}
rowString += "\n"; // after 'num' chars added to row, add new line to board
}
console.log(rowString);
The (height+row) % 2 == 0 on line 5 is important, as it determines whether it adds a " " or # to the rowString based on the height and row value. If it was just based on height you'd get alternating columns of #'s and " ", or if it was just based on width you'd get alternating rows of " " and #. If you consider the first point; height 0 width 0, it would evaluate even, height 1 width 1, odd etc.. next row height 1 width 0, odd etc... This ensures that your board is scalable.
Here's my own code
let size = 8;
let fill = '#'
let startWithSpace = true;
let addSpace = true ;
let board = '' ;
for(let i = 1; i <= size ; i++)
{
let row = '' ;
for(let column = 1; column <= size ; column++)
{
if(addSpace)
{
row += ' ' ;
addSpace = false ;
}
else
{
row += fill;
addSpace = true;
}
}
if(startWithSpace == true )
{
addSpace = false;
startWithSpace = false;
}
else
{
addSpace = true;
startWithSpace = true;
}
board+=row + "\n" ;
}
console.log(board)
Another one
let size = 16 ;
let fill = '#' ;
let space = " " ;
let board = ''
for(i = 1; i <= size ; i++)
{
for(c = 1; c <=size ; c++)
{
board += (i + c) % 2 == 0 ? space : fill ;
}
board += "\n" ;
}
console.log(board)
Here's my approach. I've added a detailed description in the JSDoc.
/**
* Eloquent JavaScript - Chapter 2 - Program Structure (Chessboard)
*
* x = 8
*
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
* # # # #
*
* Approach used:
*
* - If size of grid passed is 8, we'll have an 8x8 grid
* - Initialize an empty string
* - Loop through the grid size
* - If even iterator, start the row with a space, loop through (grid size - 1) and keep appending a '#'
* - If odd iterator, start the row with a '#', loop through (grid size - 1) and keep appending a space
* - After the inner loop finishes, we need to start a new line, so append '\n'
* - Once the loop has finished, we just return the result and that should be our required pattern
*
*
* #param x Size of grid being displayed
*
*/
function chessboard(sizeOfGrid) {
var result = ''
var charHash = '#'
var charSpace = ' '
var charNewLine = '\n'
var remainderSize = sizeOfGrid - 1
var i, j
for(i = 0; i < sizeOfGrid; i++) {
if(i%2 === 0) {
result += charSpace
for(j = 0; j < remainderSize; j++) {
if(j % 2 === 0) {
result += charHash
} else {
result += charSpace
}
}
} else {
result += charHash
for(j = 0; j < remainderSize; j++) {
if(j % 2 === 0) {
result += charSpace
} else {
result += charHash
}
}
}
result += charNewLine
}
return result
}
var result = chessboard(8)
console.log(result)
I have solved it using a Sting method called repeat()
Program goes as follows,
const pattern1 = ' #';
const pattern2 = '# ';
const binding = 4;
for(let i=1; i<9; i++){
if(i % 2 !== 0){
console.log(pattern1.repeat(binding));
}else{
console.log(pattern2.repeat(binding));
}
};
The output would be,
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Here's my approach:
const size = 8;
let board = "";
for (let i = 0; i < size; i++) {
board += `${(i % 2 === 0 ? " #" : "# ").repeat(size/2)}\n`;
}
console.log(board);
Here is my solution:
let before = '# '
let after = ' #'
let size = 8
for (let i = 1; i <= size; i++){
let pattern = ''
for(let x = 1; x <= size/2; x++){
if(i%2===0){pattern+= before}
else{pattern+= after}
}
console.log(pattern)
}