Chapter 2 Exercises

Hi Iris,

I loved your Chess Board solution. I’ve been struggling with this exercise and found your code very helpful. Thanks!

2 Likes

Hi Guatemala,

I’ve found the solution. I had space between the variable.
var text to display = “hello”;

But it should not contain a distance like here
var texttodisplay = “hello”;

cheers from Austria

1 Like

Hey there,

I would like to add to @Fernando , that while you are learning and getting accustomed to the diagrams and how to explain code in human language/drawings. Just embrace the information overflow and celebrate the minor victories! Bit by bit things will start to fall into place and make sense.

I greatly encourage people to use paper and pen when you’re stuck. And when stuck leave it be for a few hours or a day.

honestly everyone, i have been struggling with these exercises for the past, not joking 7 days!!! ive been stuck on this chapter trying to learn and grasp JS coding thus far and I could not do the exercises on my own, i had to google the code and after seeing what i had to code to make the last exercise specially! i was very discouraged to find how much code it would have taken me to solve that. I am feeling a bit discouraged after this, can anyone help me, point me in the right direction, i keep reading over and over and just cannot grasp it all, i feel that i would do better if i was actively practicing and coding everyday but i currently do not work in computer programming, is there any app or option out there that i can use to become more fluent with this where i am constantly practicing and coding? i learn better when it is hands on. thank you.

Good luck ItsBad! Just keep on exploring it’s not as bad as it seems!

Example chessboard variable width and height:

var width = 64;
var height = 32;
var hash;
var space;
var row = 0;

while(row<height){   
for(var column = 0; column < width; column++){
   if(row % 2 == 0){
      hash = "&ensp;";
      space = "#";
   } else {
      hash = "#";
      space = "&ensp;";
    }
  
    if(column % 2 == 0){
       document.write(hash);
    }else{
       document.write(space)
    }
  }
document.write("</br>")
row++;
}
1 Like

Hey Danny,

USER PRESSES MOUSE KEY is not a real JS function. its “human language” as an example for something that this expression could be.

because the function can’t be understood by the computer it will be skipped/get buggt shouldContinue will therefore never be changed to false.

Moreover the computer will output the following:

document.write(" counter is now “+counter+” “+texttodisplay+” ");

OUTPUT:
"counter is now “+counter+” “+texttodisplay+”"

this has to do with the “quotes”. the computer reads it as a string entirely. the string is not correctly concattinating(glueing the variable and the string).

try:
change “USER PRESSES MOUSE KEY” to count<100 for example.

and
take a look at your document.write which should be something like:

“string(letters/characters)” + variable + variable + “string(letters/characters)”

Hope you will figure it out.
Cheers!

Edit: you already did, I overlooked your answer. Kind regards!

Thank you so very much for your help. Now that you point that out, that actually makes a lot more sense. I think now that I can use functions, it would have also made more sense to use a function so it could be called instead of trying for a loop. But then again, this will be helpful for the future.

Thank you a lot for your Help!

1 Like

Hey Link,

Thanks for your effort to help me.
I’m still in the early stages of Java Script, so I’m very happy to get help from people like you.

I thought that each variable have to be surrounded by quotation marks like this example?

document.write("

counter is now " + counter + " " + texttodisplay + "

");
  // Looping a Triangle Code

  var hash = "#"
  while (hash.length <= 7)
  {
    console.log(hash);
    hash += "#";
  }

//FizzBuzz Code
for (var number = 1; number <= 100; number++){
if (number % 3 == 0 && number % 5 == 0){
console.log(“FizzBuzz”);
} else if (number % 3 == 0){
console.log(“Fizz”);
} else if (number % 5 == 0){
console.log(“Buzz”);
} else {console.log(number)};
}

//Chessboard Code
var grid = “”;
var size = 8;
var height = 0;
var width;
while (height < size)
{
if (height % 2 == 0)
{
for (width = 0; width <= size; width++)
{
if (width % 2 == 0)
{
grid += " ";
}
else grid += “#”;
}
}
else
{
for (width = 0; width < size; width++)
{
if (width % 2 == 0)
{
grid += “#”;
}
else grid += " ";
}
}
console.log(grid);
grid = “”;
height++;
}

Hi Fernando

Thanks for the support, saw your solutions and explanations and thought they were really good.

1 Like

My noob logic made me come up with this. (only first part)


for (let n = 1; n <= 8; n++) {
let output = “”;
if (n % 2 == 0) output += "# # # # “;
if (n % 2 == 1) output += " # # # #”;
console.log(output);
}

1 Like

Triangles

/*
       * Repeats the value of the string toRepeat numTimes times.
       * Returns this result as a string. 
       */
      function repeat(toRepeat, numTimes){
        // use new Array() per https://stackoverflow.com/a/10050831
        // the initial values are blank.
        let arr = new Array(numTimes);
        // join turns array into string.
        // source: https://www.geeksforgeeks.org/javascript-array-join-method/
        // since the elements in arr are empty
        // this repeats toRepeat numTimes with nothing else.
        return arr.join(toRepeat);
      }
      /*
       * Creates a triangle out of the string toRepeat using console.log().
       * On the ith line of the triangle, toRepeat will be repeated i times. 
       */
      function triangle(toRepeat, numLines){
        for(let i=1; i<=numLines; i++){
          console.log(repeat(toRepeat, i));
        }
      }
      triangle("#", 7);

FizzBuzz
There are two main ways to do FizzBuzz: concatenation with an empty check at the end (to determine if the concatenation should be printed or the number should be printed), or check all possible combinations of factors.

The algorithm for the concatenation approach:

ret = ""
if (number is divisible by 3): append "Fizz" to ret
if (number is divisible by 5): append "Buzz" to ret
// repeat for other factors as needed
if(ret is empty): print number
else: print ret

The algorithm for the “all possible combinations” approach:

// must try the combinations in 
// largest (most factors multiplied together) to 
// smallest (fewest factors multiplied together)  order. 
if (number is divisible by 3 * 5): print "FizzBuzz"
else if (number is divisible by 3): print "Fizz"
else if (number is divisible by 5): print "Buzz"
else: print number

The former approach scales better. My JavaScript implementation of the former approach (below) uses recursion to generate each line (so variables don’t have to be mutated to make a line) and a for loop to generate the lines. It also allows you to specify the factors (e.g. 3 and 5) and the corresponding words (e.g. “Fizz” and “Buzz”).

/* 
       * Completes FizzBuzz by concatenating the acc words together,
       * or by converting numToCheck to a string. 
       */
      function completeFizzAcc(numToCheck, acc){
        if(!acc || !acc.length){
          // empty acc: no factors ever matched. Return the numToCheck.
          return numToCheck.toString();
        } else{
          // non-empty acc: factor(s) matched. concat with empty str.
          return acc.join(""); 
        }
      }
      /* 
       * Tests the [factor, word] entry at the head of factorsToWords
       * which is an array of [factor, word] entries.
       */
      function testHeadFactor(numToCheck, acc, factorsToWords){
        let factorsToWordsHead = factorsToWords[0];
        let factorsToWordsTail = factorsToWords.slice(1);
        // each element in factorsToWords is a [factor, word] array.
        let factor = factorsToWordsHead[0];
        let word = factorsToWordsHead[1];
        
        if(numToCheck % factor == 0){
          //found factor; append word and continue
          return fizzAcc(
            numToCheck, acc.concat(word), factorsToWordsTail
          );
        } else{
          //didn't find factor; continue without appending word.
          return fizzAcc(
            numToCheck, acc, factorsToWordsTail
          )
        }
      }
      /*
       * Functional version of fizzBuzz.
       * This takes in the current numToCheck 
       * (the number you need to figure out how to handle in FizzBuzz)
       * and an acc(umulator) array with the words matched before.
       * factorsToWords is an array of [factor, word] arrays. 
       */
      function fizzAcc(numToCheck, acc, factorsToWords){
        if(!isEmpty(factorsToWords)){
          return testHeadFactor(numToCheck, acc, factorsToWords);
        } else{
          return completeFizzAcc(numToCheck, acc);
        }
      }
      /* 
       * Entry point for performing fizzbuzz on a given numberToCheck.
       */
      function fizzLine(numToCheck, factorsToWords){
        return fizzAcc(numToCheck, [], factorsToWords);
      }
      let factorsToWords = [
        [3, "Fizz"],
        [5, "Buzz"]
      ];
      for(let i=1; i<=100; i++){
        console.log(fizzAcc(i, [], factorsToWords));
      }

Chessboard
I took a similar approach with the chessboard.

      /*
       * This is the function to call to make a row in a chessboard. 
       * rowLength is the number of tiles in the row
       * symbols is an array of string symbols to show for the tiles.
       * The pattern of symbols will be repeated to make the row.
       * Returns a string representing the row.
       */
      function makeChessboardRow(rowLength, symbols){
        //defensives
        if(rowLength <= 0){
          return "";
        }
        if(!symbols || !symbols.length){
          return "";
        }
        
        //calculations
        let symbolIndex = rowLength % symbols.length;
        let tailSymbol = symbols[symbolIndex];
        let headSymbols = makeChessboardRow(rowLength-1, symbols);
        return headSymbols + tailSymbol;
      }
      /**
       * This is the function to call to make a chessboard. 
       * numRows is the number of rows
       * rowLength is the length of each row.
       * symbolsPerRow is an array of arrays. 
       * Each array in symbolsPerRow describes a pattern for a row
       * (a pattern to pass to makeChessboardRow). 
       * The symbolsPerRow will be repeated to make the chessboard.
       * Returns a string representing the chessboard.
       */
      function makeChessboard(numRows, rowLength, symbolsPerRow){
        if(!numRows || !rowLength){
          return;
        }
        if(!symbolsPerRow || !symbolsPerRow.length){
          return;
        }
        for(let i=0; i<numRows; i++){
          let currentSymbolsIndex = i % symbolsPerRow.length;
          let symbols = symbolsPerRow[currentSymbolsIndex];
          console.log(makeChessboardRow(rowLength, symbols));
        }
      }
      let symbolsPerRow = [
        [" ", "#"],
        ["#", " "]
      ];
      makeChessboard(8, 8, symbolsPerRow);

My answer:
// TRIANGLES
let counter=0; statement="#"
for(let count=0;count<7;count++){
while(counter<count){
statement=statement+"#"
counter++
}
document.write(statement + “< br >”)
}
// FIZZBUZZ
for(let count2=1;count2<101;count2++){
if (count2%3==0 && count2%5==0) {
document.write(“FizzBuzz” + “< br >)
} else if (count2%5==0 && !count2%3==0) {
document.write(“Buzz” + “< br >”)
} else if (count2%3==0 && !count2%5==0) {
document.write(“Fizz” + “< br >”)
} else {
document.write(count2 + “< br >”)
}
}
//CHESSBOARD
let max=4
let grid1=”# "
let grid2=" #"
for(let count=0;count<max-1;count++){
grid1=grid1+"# "
grid2=grid2+" #"
}
for (let count=0;count<2*max;count++){
if (count%2==0){
document.write(grid1 + “< br >”)
} else if (count%2==1) {
document.write(grid2 + “< br >”)
}
}

My solutions

FizzBuuz

var number = 0;
while (number <= 99){
number += 1;
if (number % 3 == 0 && number % 5 == 0){
console.log(“FizzBuzz”);
else if (number % 3 == 0){
console.log(“Fizz”);
else if (number % 5 == 0){
console.log(“Buzz”);
else console.log(number);
}

I was cracking my head about how I could simplify the code, I knew there had to be a simpler way to combine the outputs.
After seeing the solution on Eloquent JavaScript, I realised that I could have made more use for an empty string value and add on to it.
Another key takeaway was the fact that the empty string value gives a false Boolean value, and that meant that we could have used the logical OR operator.

Chessboard

I was doing the exercises before I looked at Ivan's video, and had no idea how to start, especially for the general case where the size can be any size, so I looked at the solution. Still trying to wrap my head around it, but after looking at Ivan's video on how to loop a triangle, I realised that it is about the same for the board. Will be giving it another shot again!

Triangle Loop

var row = 0;

  for (row = 0; row < 7; row++) {


    var hashTag = "#";

    for (line = 0; line < row; line++) {
        hashTag += "#"
    }
    console.log(hashTag);
    document.write("<p>" + line + "hashTag" + "</p>");
  }

FizzBuzz

for (i = 1; i <= 100; i++) {
  if(i%3 == 0 && i%5 != 0) {
    console.log("Fizz");

  } else if (i%5 == 0 && i%3 != 0) {
    console.log("Buzz");

  } else if (i%5 == 0 && i%3 == 0 ) {
    console.log("FizzBuzz");
    
  } else {
    console.log(i);
  }
}

Chapter 2 Exercises:
Looping a triangle:
This is what I put between the script tags:
var note = ’ ’
for(var i = 0; i < 7; i++){
console.log(note += ‘#’);

        }

FIzzBuzz:
var number = 101;

  for(i=1; i<number; i++){

    if ( i%3 == 0 && i%5 ==0){
    console.log("FizzBuzz");
    }
    else if (i%3 ==0){
    console.log("Fizz");
    }
    else if (i%5 ==0){
      console.log("Buzz");
    }
    else{
    console.log(i);
    }
  }

Chessboard (spent a lot of time on this one - suggested video from Brandon_Clark on June 21st was very helpful):
var size = 8;
var board = “”;

for(var y = 0; y < size; y++){
  for(var x=0; x< size;x++){
    if((x+y) % 2==0){
      //" "
      board += " ";
    }
    else {
      //"#"
      board += "#";
    }
  }
  board += "\n"
}
    console.log(board);

This forum is amazing, showing an almost infinite number of ways to solve these exercises. Thank you all.

When I open the Atom file in Firefox, the functions are executed. However, when I open it in the Chrome Browser, the same code appears as in the program. ?
What is the difference between console.log and document write?
I’m grateful for any help!

FizzBuzz
var numRows = 100;
for (var counter = 1; counter < numRows; counter++)
{
if (counter % 3 == 0 && counter % 5 != 0) {
console.log (“Fizz”);
} else if (counter % 5 == 0 && counter % 3 != 0) {
console.log (“Buzz”);
} else if (counter % 5 == 0 && counter % 3 == 0) {
console.log (“FizzBuzz”);
} else {
console.log (counter);
}
}

Chessboard
var size = 8;
var chess = “”;
for (var row = 0; row < size; row ++) {
for (var column = 0; column < size; column ++) {
if ((row + column) % 2 == 0){
chess += " ";
} else {
chess += “#”;
}
}
chess += “\n”;
}
console.log (chess)

FIZZ BUZZ
for(a= 0; a<= 100; a++){
console.log(a);
if (a%3 == 0){console.log(“Fizz”);
}else if(a%5 == 0){console.log(“Buzz”);
}

         if (a%3==0 && a%5==0) {console.log("FizzBuzz");
        }
       }

CHESSBOARD- Struggled***

for (line1=0; line1<8; line1+=2)
{let b = “#”;
console.log(" " + b);}

      for (line2 = 9; line2<16; line2+=2)
      {let b= "#";
       console.log(b + " ");}

       for (line3=17; line3<24; line3+=2)
       {let b = "#";
        console.log(" " + b);}

        for (line4=25; line4<32; line4+=2)
        {let b= "#";
         console.log(b + " " );}

         for (line5=33; line5<40; line5+=2)
         {let b = "#";
          console.log(" " + b);}

          for (line6=41; line6<48; line6+=2)
          {let b= "#";
           console.log(b + " " );}

           for (line7=49; line7<56; line7+=2)
           {let b = "#";
            console.log(" " + b);}

            for (line8=57; line8<64; line8+=2)
            {let b= "#";
             console.log(b + " " );}

console.log() - Writes information to the browser console, good for debugging purposes

document.write() - Write directly to the HTML document

I hope that help :slight_smile:

FizzBuzz

Hi Marija,
Thanks for your answer. Now I have an idea :slight_smile: Can you tell me why the Atom file does not run in the Chrome Browser?