Chapter 2 Exercises

FizzBuzz A:

var num = 0;

      for(var counter=0; counter<100; counter++){
        num += 1;
        if(num % 3 == 0) {
          var toPrint = "Fizz";
        } else if(num % 5 == 0) {
          var toPrint = "Buzz";
        } else {
          var toPrint = num;
        }
        console.log(toPrint);
      }

Fizzbuzz B:

var num = 0;

  for(var counter=0; counter<100; counter++){
    num += 1;
    if(num % 3 == 0 && num % 5 == 0){
      var toPrint = "FizzBuzz";
    } else if(num % 3 == 0) {
      var toPrint = "Fizz";
    } else if(num % 5 == 0) {
      var toPrint = "Buzz";
    } else {
      var toPrint = num;
    }
    console.log(toPrint);
  }

Chessboard A:

var numRows = 8;
      var num = 0;

      for(var counter=0; counter<numRows; counter++){
        num += 1;
        if(num % 2 == 0){
          var toPrint = "# # # # ";
        } else {
          var toPrint = " # # # #";
        }
        console.log(toPrint);
      }

I took an easy way round the first part of the chessboard exercise, but had a bit hard time with the second part. I had to check it out from the answers since I didn’t come up with the logic of when to draw “#” and when to draw " ".

2 Likes

Hello all,

While I am still workiung on this, I was hoping someone might take a look at my initial attempt at eh chessboard puzzle and tell me why it doesn’t work? I can see that it is much clunkier than the actual solutions, but I would like to better understand the logic failings behind it.

let size = 8
let width = 0
let evenline = " ";
let oddline = “#”;

for(width = 0; width <= size; width = width + 1 ) {
let evenline = " "
if (evenline.length <= size) {
let evenline = evenline + “#”;
if (evenline.length <= size) {
let evenline =evenline + " ";
if (evenline.length > size) {
let evenline =evenline + “\n”;
}}}

let oddline = “#”
if (oddline.length <= size) {
let oddline = oddline + " ";
if (oddline.length <= size) {
let oddline = oddline + “#”;
if (oddline.length > size) {
let oddline = oddline+ “\n”;
}}}

for (hight = 0; hight <= size; hight ++) {
console.log(evenline);
hight ++;
if (hight <= size) {
console.log(oddline)
}
}}

Thanks in advance!

Cheers,
ADC

1 Like
<html>
     <body>
          <table>
               <tr>
                    <td>Maximum Rows</td>
                    <td><input type="number" name="max_rows" value="0"></td>
                    <td><button type="button" name="button" onclick="show()">Generate</button></td>
               </tr>
               <tr><td colspan="3"><code id="display"></code></td></tr>
          </table>

          <script>

               function show() {
                    var response = "<i>no-text</i>";
                    var max_rows = document.getElementsByName("max_rows")[0].value;

                    if (max_rows >= 1) {
                         var response = "";
                         for (var y = 1; y <= max_rows; ++y) {
                              for (var x = 0; x < y; ++x) {
                                   response += "#";
                              }
                              response += "<br />";
                         }
                    }

                    document.getElementById("display").innerHTML = response;
               }
               show();

          </script>
     </body>
</html>
2 Likes

Triangle Loop

var rowmax = 7;
for (var row = 0; row<rowmax; row++) {
var output = “#”;
for (var column = 0; column < row; column++) {
output += “#”;
}
console.log(output);
}

Fizzbuzz

for (let numb = 1; numb<= 100; numb++) {
let result = " ";
if (numb % 3 ==0) result += “Fizz”;

if (numb % 5 ==0) result += "Buzz";l

console.log(result || numb);
}

The chessboard exercise chewed me up and spit me out…I struggled…well, struggling

2 Likes

It takes a lot of mental crunching to get these algorithms right. But once you understand how to think for such questions, you’ll find yourself in a very good position. Hang in there, moulding such mental models in your head takes time but is definitely worth it. :muscle:

Have a great day. :smile:

2 Likes

I’m still hanging on, just moving a bit slow; thanks for the motivation. You enjoy your day as well

  1. for (let line = “#”; line.length < 8; line += “#”)
    console.log(line);

2.for (let n = 1; n <= 100; n++) {
let output = “”;
if (n % 3 == 0) output += “Fizz”;
if (n % 5 == 0) output += “Buzz”;
console.log(output || n);
}
3. let size = 8;

let board = “”;

for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if ((x + y) % 2 == 0) {
board += " ";
} else {
board += “#”;
}
}
board += “\n”;
}

console.log(board);

1 Like

/example 1/

for(let triangle="";triangle.length<8;triangle+="#"){
console.log(triangle)}

/ex2/
for(let a2=1; a2<101; a2++){
if(a2%3==0 && a2%5==0){
console.log(“FizzBuzz”);}
else if (a2%3==0) {
console.log(“Fizz”);}
else if(a2%5==0) {
console.log(“Buzz”);}
else{
console.log(a2)
}
}

/*ex3- thought the function had to be able to take any dimensions of rows and columns */

chessDimensionsEfficient= function(rowNumberM,colNumberM){
/make up of odd lines of chess board/
oddMakeUp= function(colNumberM){
odd_row=""
for(let cols=1; cols<=colNumberM; cols++){

/even col/
if (cols%2==0){
odd_row+="#"
}

/odd col/
else{
odd_row+=" "
}
if(cols==colNumberM){
console.log(odd_row+"\n")}
}}

/make up for even lines of chess board/
evenMakeUp= function(colNumberM){
even_row=""
for(let cols=1; cols<=colNumberM; cols++){

  /*even col*/
  if (cols%2==0){
    even_row+=" "
    }
  /*odd col*/
  else{even_row+="#"}
  if(cols==colNumberM){
    console.log(even_row+"\n")}
  }

}

/*printing rows */
printRows= function(rowNumberM){
for(rowp=1; rowp<=rowNumberM; rowp++)
if(rowp%2==0){
console.log(evenMakeUp)}
else{console.log(oddMakeUp)}
}
}

2 Likes

I believe it is the or function, it will evaluate what is to its left and if there is no ‘output’ then it will evaluate what is to its right. So it will print out number n if there is no output (fizz, buzz, or fizzbuzz)

1 Like

I understand it now. Thanks for your reply!

1 Like

Looping a triangle

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

FizzBuzz

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

Chessboard - my algorithm is not as efficient as the author’s but it works :slight_smile:

 var size = prompt("Please select an integer value to define width and height of the grid.");
 var board = "";

     for(var row = 0; row < size; row++){
         for(var column = 0; column < size; column++){
           // Distinguish between rows with even and odd index value
           if(row % 2 == 0){
             // Distinguish between columns with even and odd index value
             if(column % 2 == 0){
               board += " ";
             } else{
               board += "#";
             }
           }
           // Distinguish between rows with even and odd index value
           else{
             // Distinguish between columns with even and odd index value
             if(column % 2 == 0){
               board += "#";
             } else{
               board += " ";
             }
           }
         }
         board += "\n";
       }
       console.log(board);
1 Like

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

My chessboard is suffering… Instead of putting the output into 8 rows, it does it all in one.
Chessboard:
var size = 8; var print = “”;
for (x = 0; x < size; x++){
for (y = 0; y < size; y++){
if ((x+y)%2==0) print += " "; else (print += “#”);
}
} console.log(print);

Good Lord!!! Getting my old creative brain to think in logic is seeming more difficult than previously thought. lol. (Anyone Else have this issue?) I did find myself able to break the problem down into what i needed to solve for, and was able to learn a lot though by searching how to write different parts of the code in a google search. So here is what i got!:

FizzBuzz:
let output = “”
for(number = 0; number<=100; number++){

  if(number % 3 == 0 && number % 5 == 0){
    output += number + "FizzBuzz";
  }
  else if(number % 3 == 0){
    output += number + "Fizz";
        }
  else if(number % 5 == 0){
    output += number + "Buzz";
  }

}
console.log(output)

Chess Board:
let grid = 8;

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

I knew some programming basics in python. But I forgot a lot of it since many years have passed. I think there are some differences in javascript from python. For example I don’t remember ++ in Python and this caused me some confusion with += operator. Also I think this || is like or in Python. I still don’t understand the meaning of let statement but I will look into it tommorow when I will also complete the chessboard exercise. Overall I quite enjoy relearning programming again :slight_smile:

fizzbuzz1

  for (n = 1; n <= 100; n++) {
    print = "";
    if (n % 3 == 0) print += "Fizz";
    if (n % 5 == 0) print += "Buzz";
    console.log(print || n);
  }

fizzbuz 2

  for (n = 1; n <= 100; n++) {
    print = "";
    if (n % 3 == 0 && n % 5 == 0) print += "FizzBuzz";
    console.log(print || n);
  }
1 Like

Chessboard:

  //Example 1
  size = 8;
  board = "";
  for ( a = 0; a < size; a++) {
    for ( b = 0; b < size; b++) {
      if ((b + a) % 2 == 0) {
        board += " ";
      } else {
        board += "#";
      }
    }
    board += "\n";
  }
  console.log(board);


  //Example 2  with prompt specific inputs
  let height = prompt("insert the height");
  let width = prompt ("insert the width");
  let board = ""
  for ( a = 0; a < height; a++) {
    for ( b = 0; b < width; b++) {
      if ((b + a) % 2 == 0) {
        board += " ";
      } else {
        board += "#";
      }
    }
    board += "\n";
  }
  console.log(board);
1 Like

1.Looping a Triangle

for(let triangle = “#”;triangle.length<=7;triangle+="#")
console.log(triangle);

  1. Fizz Buzz

for (var i=1; i < 101; i++){
if (i % 15 == 0) console.log(“FizzBuzz”);
else if (i % 3 == 0) console.log(“Fizz”);
else if (i % 5 == 0) console.log(“Buzz”);
else console.log(i);
}

  1. Chessboard

var size = 8;
var board = “”;

// Outerloop for rows
for (let i = 1; i <= size; i++) {
// inner loop for columns
for (let j = 1; j <= size; j++) {
if ((i+j) % 2 == 0) { // check if col is even
board += " ";
} else { // if col is odd
board += “#”;
}
}
board += “\n”; // jump to next row
}
console.log(board);

1 Like

Triangle Loop

//Looping a triangle
          var num_rows = 7;
          for(var row = 0; row < num_rows; row++){
            var toPrint = "#";
            for(var column = 0; column < row; column++){
              toPrint += "#";
            }
            console.log(toPrint);
          }

FizzBuzz

for(var num=0; num<100; num++){
            if(num % 15 == 0){
              console.log("FizzBuzz");
            }
            else if(num % 5 == 0){
              console.log("Fizz");
            }
            else if(num % 3 == 0){
              console.log("Buzz");
            }
            else{
              console.log(num);
            }
          }

Chessboard

          size_height = 8;
          size_width = 8;
          var board = "";
          for(var count_row = 0; count_row < size_height; count_row++){
            for(var count_column=0; count_column<size_width; count_column++){
              if((count_row + count_column) % 2 == 0) {board += " ";}
              else {board += "#"}
            }
            board += "\n";
          }
          console.log(board);
1 Like

1.) for (var triangle = ‘#’; triangle.length <=7; triangle += “#”)
console. log (triangle);

  1. :man_shrugging:t3:

var size = 8; 

var board = "";

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);
1 Like
  1. Looping a triangle
    var max_sign_lenght=7;
    for (var i = 0; i<max_sign_lenght; i++) {
    var sign="#";
    for (var j = 0; j<i; j++) {
    sign+="#";}
    console.log(sign);
    }
  2. FizzBuzz
    for (var i = 1; i <=100; i++) {
    if (i%3==0 && i%5==0) {
    console.log(“FizzBuzz”);
    }
    else if (i%3==0){
    console.log(“Fizz”);
    // continue;
    }
    else if (i%5==0){
    console.log(“Buzz”);
    // continue;
    }
    else{
    console.log(i);
    }
    }
  3. Chessboard
    version 1
    var row="# # # #";
    for (var i = 0; i <8; i++) {
    if (i%2!=0){
    console.log(" “+row);
    }
    else {
    console.log(row+” ");
    }
    }

version 2
var field = “”;
for (var x = 0; x < 8; x++) {
for (var y = 0; y < 8; y++) {
if ((x + y) % 2 == 0)
field += " ";
else{
field += “#”;
}
}
field += “\n”;
}
console.log(field);

1 Like

It took me a few days to understand these solutions— I didn’t want to just copy and paste. I found a great youtuber to help me out with videos. Maybe these videos are already in the course. Don’t remember.

  1. triangle loop: This is simple code for console:

for (var line = “#”; line.length < 8; line += “#”)
console.log(line);
/////explanation: https://www.youtube.com/watch?v=bci_CJbFo-Y&t=583s

  1. Chessboard loop: This is simple code for console:

let spaceHashtag = " #";
let hashtagSpace = "# ";

for (let i = 0; i < 8; i ++)
{
if (i % 2 == 0)
{ console.log (spaceHashtag.repeat (4)); }
else { console.log (hashtagSpace.repeat (4));}
}
/////with explanation of book code and this simpler code
https://www.youtube.com/watch?v=JXyAuAsF1vw

3.FizzBuzz code:

for (let n = 1; n < 100; n ++)
{
let output = “”;
if (n % 3 == 0) output += “Fizz”;
if (n % 5 == 0) output += “Buzz”;

console.log (output || n);
}
///explanation: https://www.youtube.com/watch?v=PhL_XoHSfkc

2 Likes