Chapter 2 Exercises

Hi thecil, thanks for the reply.

this excerice is the fizbuzz exercise.

i kinda understand now, if num%3== means num divided by 3 has a remainder of zero. correct?

1 Like

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");
  }
  else if (i % 5 == 0){
    console.log("Buzz");
  }

  else{
    console.log(i);
  }
}

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

ChessBoard

var num_row = 8;

  var textToPrint = "";
  for(var row = 0; row < num_row; row++){
    for (var column = 0; column < num_row; column++){

    if ((column+row) % 2 == 0){
      textToPrint += " ";
    }
    else{
      textToPrint += "#";
    }
  }
    textToPrint += "\n";
  }
  console.log(textToPrint);
1 Like

Oooops! Fixed the missing “=” bug in FizzBuzz:

for (let number=1; number <= 100; ++number) 

Quick modification to the Chessboard to also adjust the column number (assuming even rows and columns):

let chessColumns = 8;
let oddRowString  = " #".repeat(chessColumns/2);
let evenRowString = "# ".repeat(chessColumns/2);

But I don’t like it. So I made a new implementation (after reading again the exercise’s statement, now till the end):

      var boardSize = 8;
      // position 0,0 --> top left
      // position n,n --> bottom right

      function getWhichCellNeedsToBePrintedAtPosition(x, y) {
        return (x + y) % 2 ? "#" : " ";
      }

      for (var x = 0; x < boardSize; ++x) {
        var column = "";
        for (let y = 0; y < boardSize; ++y) {
          column += getWhichCellNeedsToBePrintedAtPosition(x, y);
        }
        console.log(column);
    }

Thanks!
//Dani

2 Likes

Again, another very innovative and creative solution! :smiley:

So good that you’re reflecting on your code and then attempting to find ways to improve on it, or even just do it differently. That’s a sure way to learn loads, progress quickly, and remember more of what you’ve already learnt. :+1:

Just one observation, if I may… I wouldn’t get into the habit of writing such long function names.

:wink: Try to keep them shorter while still communicating what they do. That makes you code “cleaner” and easier to read and develop further (especially for others).

2 Likes

Great work @Will_Day! :smiley:

By the way, I’m not sure if you know, but before you type in your code to post it here in the forum, click on the </> icon in the menu at the top of the text editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted, which is then also easier for you to organise with the correct spacing and indentation etc. For your Chessboard you should then end up with something like:

var num_rows = 8;     // Number of rows.
var toPrint = "";     // innitialized toPrint as blank.
var num_cols = 8;     // Number of columns.

/* Did the for statement for the rows first
because we need to iterate inside the row. */
for (var rows = 0; rows < num_rows; rows++) {
   /* The columns are just how many 
   iterations until the end of the row. */
   for (var cols = 0; cols < num_cols; cols++){
      if ((rows + cols) % 2 == 0) toPrint = toPrint + "#";
      else toPrint = toPrint + " ";
   }
   // After the 8th iteration the newline will be initiated.
   toPrint = toPrint + "\n";
}
console.log(toPrint);

Be careful with your comment syntax, I had to add a few asterisks to your forward slashes to get
/* ... */   so I could get your code to run without the comments interfering :wink:

Keep on learning! You’re doing great!

2 Likes

Great! :muscle:
Did you try FizzBuzz?
By the way have a look at this post. It explains how and why you should format your code in the forum posts. It also gives an example of what your code should end up looking like. Your actual code is different (and, of course, the comments are optional) but it still shows you how clearer it is with the formatting.

1 Like

Hey @Davide_Coltro! Great solutions! :muscle:

Excellent formatting too… spacing, indentation, nesting etc. :+1:

The only formatting improvement I can see you could make, is with the if...else statements in your second for loop: it would be even clearer if you indent them once more, so that they are clearly nested within the second for loop. Then you can also bring that same for loop’s closing curly brace into line.

2 Likes

Thanks jon_m. I am going to give it a try!

2 Likes

Here is my individual solution for the Chessboard exercise. I wanted to make it as simple and concrete as possible and it took me a couple of days, but I finally got it. I hope it is of any help to all of you.

Chessboard

let line1="# # # #";
let line2=" # # # #";
board="";
for (let board=0; board<8; board++){
if(board%2==0){
console.log(line2);
}else{
console.log(line1);
} board += “\n”;
}console.log(board);

1 Like
let size = 8;
let board ="";
for (let x = 0; x < size; x++){
for (let y = 0; y < size; y++){
if ((y + x) % 2 == 0){
board += " ";
} else {
board += "#";

}
}
board += “\n”;
}
console.log(board);

Looking much better!

1 Like

…and this is my personal solution for the FizzBuzz. Hope you are interested.

FizzBuzz

let counter=0

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

Triangle was shown to Ivangelists already…

Fizzbuzz: Why does the divisible by 3 & 5 check not work in the if statement?

image

Chessboard: I made it ask size of board and works fine in console but why is document.write not printing the first space in evenlines if I would like to display it on a site, not in the console?

And the most important question of all: If I copy&paste my code here, it doesnt show ( I guess this site interprets it as code). So how do you guys write your code in the comments? I have to load a screenshot instead of real text to have it shown…

Sorry, noob shit, but better get it straight, keeps buggin me. Thanks Ivangelists. Let’s Rock!

Edit: Sorry, screen of site vs. console print:

1 Like

If you click this you will see this
(``)the 3rd ` i left it because it turns it in preformatted text although i put it in ( )
type or paste code here
(```)
delete the type … and replace it with your code or make it manually three of them space and then code at the end again :upside_down_face: :sweat_smile: hope it helped, don’t worry everybody ask this question at the begining if never had contact with computer language :wink: :+1:

type or paste code here

preformatted text

1 Like

Looping Triangle:

var num = 7;
        for (var row = 0; row < num; row++) {
            var print = "#"

            for (var col = 0; col < row; col++) {
                print += "#"
            }
            console.log(print)
        }

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");
            } else if (i % 5 == 0) {
                console.log("Buzz");
            } else {
                console.log(i);
            }
        }

ChessBoard

  var size = 8;
        var chessboard = "";
        for (var row = 0; row < size; row++) {
            for (var col = 0; col < size; col++) {
                if ((row + col) % 2 == 0) {
                    chessboard += " ";
                } else {
                    chessboard += "#";

                }
            }
            chessboard += "\n";
        }
        console.log(chessboard);
1 Like

im so confused as to why you have entered this at the end. i took it off and i saw the effect, but what the logic?

 // After the 8th iteration the newline will be initiated.
   toPrint = toPrint + "\n";
}

for (let line = "#"; line.length < 8; line += "#")
  console.log(line);

1 Like

Fizzbuzz


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


   }else if(number%3==0){
     console.log("fizz");


   }else
     console.log(number);
 }

Took a bit to get this one. I had to look at someones elses answer honestly

1 Like

I have been looking again at the loops. Ivan put a lot of emphasis on them, and I see the importance of them. I believe that I have found a better solution for the chessboard puzzle. I know that what I submitted solved the issue, but this one is scalable. Feeling bad because it is taking forever to get through JS. I understand the logic, but it is so detailed, and it seems that there are several ways to solve the same problem. ;)} enjoy 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);

1 Like

Hey @ArvidK!

Nice work!..all 2 days of it! :muscle:
Impressive stuff…and I like your individual approach.

Next challenge!
See if you can adapt it so it also provides the functionality to adjust both the column and row number e.g. 4 x 4, or 10 x 10, instead of 8 x 8… there you go…there’s another 2 days fun! :wink:

By the way, also have a look at this post. It explains how and why you should format your code in the forum posts. It also gives an example of what your code should end up looking like. Your actual code is different (and, of course, the comments are optional) but it still shows you how clearer it is with the formatting… but I’d suggest looking at it AFTER you’ve had a go at the additional challenge I’ve set you, because it shows you how to do it (but there are alternatives, which, with your great individuality, I’m of course expecting)! :wink:

1 Like

You’ve nailed it, @DeCryptolorian! :muscle:
Well done!
Now let’s see if you can post your next code with some nice indentation and nesting :wink:

1 Like