FizzBuzz:
(Researched the function option, since this is asked in many interviews with options of using other numbers/values)
function FizzBuzz(value1, value2){
let returnValue = "";
for(let i = 1; i <= 100; i++){
if(i%value1==0 && i%value2==0){
returnValue += "FizzBuzz ";
}
else if (i%value1==0){
returnValue += "Fizz ";
}
else if (i%value2==0){
returnValue += "Buzz ";
}
else{
returnValue += i + " ";
}
}
return returnValue;
}
console.log(FizzBuzz(3, 5));
Chessboard (I hope the explanation on the bottom helps others. I learned it from a video, then typed it down. It helped me understand the approach. I need to understand the reasoning behind the code.
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);
/*
// set the variables:
let size = 8;
// sets a limit for the number of repetitions in the loop
let board = "";
// sets a blank placeholder to be filled with the if statements
for (let y = 0; y < size; y++) {
// y represents the vertical axis aka the rows. This creates the loop for the rows.
for (let x = 0; x < size; x++) {
// x represents the horizontal axis aka the columns. This creates the loop for the columns.
// note: this is a for loop inside another for loop.
// the “for loop of x” must complete its entire run from 0 to 8 before the “loop of y” can start its next loop, where y++
if ((x + y) % 2 == 0){
board += " ";
// when we set x + y, every second number will be divisible by 2, therefore,
// every second character will execute the " " space character,
// and each new line will alternate between and even/odd number
// board += " " -> (same as) board + " "
// we adjusted our variable to add " " space to it
NOTE: what “i%2==0” does is it determines if a number is even (==1 would determine if it’s odd). So it takes the value of i and divides by 2, then it compares the remainder against the value of 0.
} else {
board += "#";
}
// for every other number not divisible by 2(odd number), “#” will be executed
}
board += "\n";
}
// \n creates a new line
// board += “\n” is the same as -> board + “\n”
// this statement is attached to “for (let y = 0; y < size; y++)”, therefore
// it ensures that “the loop of x” runs 8 iterations (repetitions), aka 8 characters across,
before breaking into a new line.
console.log(board);
*/