TRIANGLE
I came up with a shorter and simpler solution than Ivan’s by using a single variable and the .length property, following the hint given on the book. Needless to say, I’m very happy with myself.
for (var tic = "#"; tic.length <=7; tic += "#"){
console.log(tic);
}
FIZZBUZZ (iteration 1)
for (var countAll = 1; countAll <= 100; countAll++) {
if (countAll % 3 == 0) { console.log("Fizz"); }
else if (countAll % 5 == 0) { console.log("Buzz"); }
else console.log(countAll);
}
FIZZBUZZ (iteration 2)
for (var countAll = 1; countAll <= 100; countAll++) {
if (countAll % 3 == 0 && countAll % 5 == 0) { console.log("FizzBuzz"); }
else if (countAll % 3 == 0) { console.log("Fizz"); }
else if (countAll % 5 == 0) { console.log("Buzz"); }
else console.log(countAll);
}
CHESS BOARD
After struggling with this one for days and days, i saw @iris 's brilliant answer and learned from it tremendously (thanks, @iris !). I modified it slightly, changing the variable names to make it more obvious for myself and others, tweaked the counters to start with 1 instead of 0, and switched initial placement of “#” and " " so as to start line 1 with a ‘#’ instead of a space.
Under the code, I/ve added line-by-line comments, to help myself and others. I hope someone finds this useful…
var size=8;
var str="";
for (outerLoop = 1; outerLoop <= size; outerLoop++){
if (outerLoop % 2 == 0){str += " ";}
for (innerLoop = 1; innerLoop <= size; innerLoop++){
if (innerLoop % 2 != 0){str += "#";}
else {str += " ";}
}
str += "\n";
}
console.log(str);
This is what is happening, line by line…
- Create a SIZE variable to determine the number of rows and line items
- Create an empty variable STR where line items will be concatenated
- Create OUTER loop and counter (to create ROWS)
- IF the ROW is EVEN, start with a SPACE. For the FIRST LINE, this will be FALSE, so row will begin with a ‘#’
- Create INNER loop and counter, to start concatenating LINE items within each row.
- If LINE ITEM is EVEN (which on the first instance it will be, because the first “#” was already added) add a space to the string.
- But (ELSE) on ODD line items, concatenate a space.
- CLOSING BRACKET closes the inner loop which will repeat itself concatenating a total of “less-than-SIZE” (7)
- Once out of the INNER LOOP and all 8 line items have concatenated, a line break gets added to the string.
- With the outermost closing bracket, the OUTER LOOP REPEATS 7 times ( “< size”).
- Once each OUTER LOOP HAS FINISHED, each line gets displayed on the JS console.