How can I enable Javascript Chessboard?

The new encoder here is trying to recognize JS. I have already done codecademy and am currently working on Eloquent Javascript. I finally got something together, scratching my head for a very long time ... but it won’t work! I'm not quite sure if I'm approaching this at right angles, but I know that I want to use loops to track progress through grid printing #.

Write a program that creates a line that represents an 8 × 8 grid, using newline characters to separate lines. In each position, the grid is either a space or the symbol "#". Characters should form a chessboard. Passing this line to console.log should look 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 as follows:

 # # # # # # # # # # # # # # # # # # # # # # # # # 

After a few iterations, I already learned a lot, but right now I see an error - I obviously reached the 7x7 grid instead of the 8x8 that I wanted to get. I suspect this is due to me using "<" in my loops, but not sure if there is a better way to handle this, and not just add an extra digit.

+7
source share
29 answers

Actually quite easily you need to make two loops, one for each line and the other to select the item you want for console.log (either '' or '#').

check 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 adding either ' ' or '#' to the string that being populated*/ if ((x + y) % 2 == 0) board += " "; else board += "#"; } board += "\n"; } console.log(board); 
+11
source

Here's a different approach.

Each line has four instances of either _# or #_ (where the underscore is a space).

Lines with even numbers begin with _# , and lines with odd numbers 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); 
+5
source

jsFiddle Demo

I am a fan of chess :) In chess, there is a rule "White on the right", which means that the first square of our chessboard will be "". After that, it will alternate every time there is an odd match between a row and a column.

 var board = ""; for(var i = 0; i < 8; i++){ for(var a = 0; a < 8; a++){ board += (a % 2) == (i % 2) ? " " : "#"; } board += "\n"; } 

View board, now it displays an 8x8 grid

 console.log(board); # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 

Do not substitute i for row number or a for column number. Or set both sizes :) It will work anyway. For example, a < 20 will give 20 columns

  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
+4
source

Here is the 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("")); 
+2
source
 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); 
+1
source

Use only the knowledge provided up to this point in the book. Bright 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); 
+1
source

here is my version. Not as clean and eloquent as a book alone, 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 = " "; } 
0
source
 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); } 
0
source

What is 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="" } 
0
source

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. 
0
source

So I and some coding friends went back and forth, optimizing this feature for fun and education.

I have not seen our winning solution here, so why not drop it?

 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 delete the for(n=2;2*n<s;n*=2) loops for(n=2;2*n<s;n*=2) , then it will work faster to create small boards, but saving them makes it more efficient for large boards. Ideally, you can calculate and specify threshold and skip for loops when size<threshold .

0
source

it may be late, but there are answers on the page itself: http://eloquentjavascript.net/code/

manipulate for loop / formula for understanding for example

 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); 
0
source

I tried mine with loops and a basic understanding of solving books.

 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 
0
source
 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)) } } 
0
source

Here's an alternative answer using the 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 adding either ' ' or '#' to the string that 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); 
0
source

I did the following ... It's not very eloquent, but it worked for 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);} } 
0
source

I used two independent FOR loops and it worked. We hope that independent FOR loops make it readable. The size of the board can be resized and displayed 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) } 
0
source

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) 
0
source

I created a solution using the String.repeat method, which, in my opinion, 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); 
0
source
 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); 
0
source

If someone is wondering, is there a way to do this with just 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 eg 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); 
0
source

The official solution uses the newline character /n , which I understand. Nested two for loops inside each other, you can create a whole chessboard in one line. Sure.

But if I want to build oddRow (starting with # and repeating in width) and evenRow (starting with _ and repeating in width) separately, then print each line sequentially using the new console.log function here, as I did.

The reason I take this approach was because printing a few lines of console.log was just used in Exercise 2.1 The Triangle Cycle of the same book. It seems more logical to me, and it 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); } 
0
source

Here is another simplified version:

 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); 
0
source

 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); 

(Height + row)% 2 == 0 in row 5 is important, because it determines whether it adds "" or # to rowString, based on the height and row value. If it were only based on height, you would get alternating columns # and "", or if it were only based on width, you would get alternating rows "" and #. If you consider the first paragraph; height 0 width 0, he would rate parity, height 1 width 1, odd, etc. next line height 1 width 0, odd, etc. This ensures that your board is scalable.

0
source

Here is 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) 
0
source

Other

 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) 
0
source

Here is my approach. I have added a detailed description in 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) 

0
source

On the other hand...

 var holder = ''; var len = 4; for (var count=0; count<len;count++) holder += '# ' holder += '\n ' + holder; if (holder.length > len) for (var curr=0; curr<len; curr++) console.log(holder); 
-1
source

Hehe, I think I made the most useless but working solution for this

 var string1 = " # # # #"; var string2 = "# # # # "; var i = 0; for (i = 0; i < 8; i++){ if (i % 2 === 0){ console.log(string1); } else{ console.log(string2); } } 
-1
source

Source: https://habr.com/ru/post/987165/


All Articles