Building triangle with nested loops - javascript

I'm trying to build a triangle using nested loops.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
I expected that each row is more than the last by only one "#" like this:
But this is the result I got:

The reason your code does it is you are updating line on each iteration and you keep appending to it. If you want to do the nested loops, than you need to reset the variable line each time you are in the outer loop.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line =""
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
Or you can keep what you have and dump the inner loop and every iteration you just add one character to the line.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line += "#";
triangle += line + "\n";
}
console.log(triangle);

You need to empty your line before each nested iteration. Without this you have one line and every time concatenate new items to it. Also you can leave the line variable and just use the triangle.
var triangle = '';
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
triangle += "#";
}
triangle += "\n";
}
console.log(triangle);
You can also try this solution with String#repeat
var triangle = '';
for (var row = 1; row <= 7; row++) {
triangle += '#'.repeat(row) + '\n';
}
console.log(triangle);

function triangle(num) {
for(let i = '#'; i.length < num; i+='#') {
console.log(i)
}
}

Try code below:
function generatePyramid() {
var totalNumberofRows = 7;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
output+= "# ";
}
print(output);
output="";
}
}
generatePyramid();
How it works: http://rextester.com/ULY85622

EDIT: Fixed it by just adding one line - you need to reinitialize the variable "line" after each row iteration
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line="";
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);

You need to reset line after each loop because it is accumulating all # on each cycle:
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line = "" // Add this line
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
Your code is incorrect because line follows the following steps on each cycle:
row 1: line starts as '' and ends as # (Adds #)
row 2: line starts as # and ends as ### (Adds ##)
row 3: line starts as ### and ends as ###### (Adds ###)
row 4: line starts as ###### and ends as ########## (Adds ####)
row 5: line starts as ########## and ends as ############### (Adds #####)
row 6: line starts as ############### and ends as ##################### (Adds ######)
row 7: line starts as ##################### and ends as ############################ (Adds #######)

Related

Looping a triangle from Eloquent JavaScript Variable (Eloquent JavaScript)

This is the solution:
for (let line = "#"; line.length < 8; line += "#")
console.log(line);
My question is : If line = "#", why can't line be used on the right hand side of the += operator like so:
for (let line = "#"; line.length < 8; line += line)
console.log(line);
Since you're adding line to itself each time, line will grow exponentially. Run the code here to take a look:
for (let line = "#"; line.length < 20; line += line) console.log(line)
By doing for (let line = "#"; line.length < 8; line += "#") console.log(line);
You ensure that line only increases by one "#" in each iteration.

How to print basic Christmas Tree with JavaScript?

Trying to make a simple script that draws a tree of certain height in console with simple JS loops. It should look like that.
For height = 4 :
*
***
*****
*******
so far have this but somehow it's not working:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '***';
}
for ( var k = height - 1 ; k > 0; k-- ) {
spacesBefore = space.repeat(k);
star = spacesBefore + star;
}
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
alert('Check console')
any advice where I'm wrong? thx <3
You had 2 minor problems with your code.
There should be an odd number of stars per level (1, 3, 5, 7, ...) and you were adding 3n + 1 stars which will alternate between even and odd. The change to make for that is star = star + "**" instead of ... + "***"
There is no need for the for (var k = ...) loop for counting the spaces. Your logic is right, but looping over the entire height for each row will yield you the same number of spaces per row, which is what your output is showing, which is wrong. What you want to do instead for the number of spaces is height - i - 1.
A working solution would look like the following:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '**';
}
var spacesBefore = space.repeat(height-i-1);
star = spacesBefore + star;
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
A more concise version of this code would look like the following:
function drawTree(height) {
for (var i = 0; i < height; i++) {
// 2n+1 stars per row i.e. 1, 3, 5, 7, ...
var stars = '*'.repeat(2 * i + 1);
var spacesBefore = ' '.repeat(height - i - 1);
console.log(spacesBefore + stars);
}
}
drawTree(prompt('How many levels high should be the tree?'));
Would like to calculate width first and then use that width. Spaces are depended upon width and number of * in each height.
width = height*2 - 1;
Code for tree:
function tree(h) {
let i =0, j = 1;
w = h*2 - 1;
let space = parseInt(w / 2);
while (space >= 0) {
let str = '';
for (i = 0; i < space; i++) str += ' ';
for (i = 0; i<j; i++) str += '*';
console.log(str);
// Since every next line got 2 more *
j += 2;
// Number of space reduce by 1
space--;
}
}
function drawTree(h) {
let star = "*";
let space = " ";
let spaceCount = h-1;
let starCount = 1;
for(let i = 0; i < h; i++) {
console.log(`${space.repeat(spaceCount)}${star.repeat(starCount)}${space.repeat(spaceCount)}`);
spaceCount -= 1;
starCount += 2;
}
}
drawTree(20)

How to print a half pyramid in javascript

The code works but I don't want the inner for loop to take me to the new line.
for (i = 0; i < 5; i++) {
for (j = 1; j <= i; j++) {
console.log('*');
}
console.log();
}
console.log('-----------------');
console.log will automatically break the line. Concatenate to a string instead of a log. Log at the end.
let str = '';
for(i = 0; i <= 5 ; i++) {
for(j = 1; j <= i; j++) {
str += '*';
}
str += '\n';
}
console.log(str);
You can do this way, with the help of a string variable:
for (i = 0; i < 5; i++) {
var str = '';
for (j = 1; j <= i; j++) {
str+='*';
}
console.log(str);
}
console.log('-----------------');
If you want to print at the page, use like below
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You need to break the line with the console.log you can also controle the space between * with output+='*' + " ";
function pyramid() {
var total = 5;
var output="";
for (var i = 1; i <= total; i++) {
for (var j = 1; j <= i; j++) {
output+='*' + " ";
}
console.log(output);
output="";
}
}
pyramid()
You can get rid of second for loop as follows:
var str = '';
for (i = 1; i <= 5; i++) {
str +=Array(i).join("*");
str +='\n';
}
console.log(str);
let string = "";
for (let i = 0; i < 5; i++){
string += '*';
console.log(string);
}
Output:
*
**
***
****
*****
A simple way to solve this "exercise" in JavaScript:
let width = ""
while(width.length < 6) console.log(width += `#` );
Basically, we create a string (width) and increment its value using the while loop till we hit a restriction.
I found the more typical method "bulky"(?)...plus there's the issue of not getting the exact picture of a half pyramid.
let i,j
for (i= 0; i < 6; i++){
for (j = 0; j<=i; j++){
console.log("#")
}
console.log("\n")
}
function pyramid(n){
let result = "";
for(let i=0; i<=n; i++){
result += "*".repeat(i);
result += "\n"
}
return result;
}
console.log(pyramid(5));
//OutPut
*
**
***
****
*****
As we need n number of pyramid structure with '' / '#' / any symbol. by using above code we can achieve. Here you can see we just created a function called pyramid with one parameter 'n'. and inside function we declare a variable 'result'. So inside for loop the length of 'i' is "<=n" and also you can use "repeat() method to print '' 'i' times. So if you call that function like console.log(pyramid(5)); You can able to see your Answer as expected..
shortest code:
console.log('*\n**\n***\n****\n*****');

Why is my eloquent javascript solution crashing?

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

How do I solve the Eloquent Javascript "Chess Board"?

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

Categories

Resources