Eloquent JS: Chapter 2 Exercises
Mixing it up a little bit by changing the Daily Exercise post to reflect a refresher on my JS Skills. I am reading, re-reading, Eloquent Javascript. It is a good reference for learning and one that have pointed new students towards. Along that note for current and future here are easy to understand solutions:
Looping a Triangle
Write a loop that makes n (seven initially in the exercise part one but I’m skipping to part two) calls to console.log to output the following triangle:
–
#
##
###
####
–
`
function createTriangle(max)
{
let charToPrint = “#”;
for(let i=0;i<max-1;i++)
{
console.log(charToPrint.repeat(i));
}
}
`
FizzBuzz
Write a program that uses stdout (console.log) to print all the numbers 1 to 100, with two exceptions. For numbers divisible by 3 print “FIZZ”, for those divisible by 5 print “BUZZ” and for those divisble by both print “FIZZBUZZ”. (The book calls this out as used in interviews and it has always been one of my favorite interview questions!)
`
function fizzBuzz(max)
{
for(let i=1;i<max;i++)
{
let stringToPrint = i;
if((i%3==0)&&(i%5==0))
{
stringToPrint = "FIZZBUZZ";
}else{
if(i%3==0)
{
stringToPrint = "FIZZ";
}
else if(i%5==0)
{
stringToPrint = "BUZZ";
}
}
console.log(stringToPrint)
}
}
`
Chessboard
Write a program that creates a string that represents an 8x8 grid, with newlines to seperate lines. At each position of the grid there is either a space or # char. Part 2, create a binding for size to create grids of arbitrary size.
–
#
#
#
#
–
`
function chessboard(gridSize)
{
for(let i=0;i<gridSize;i++)
{
let rowString = “”;
for(let j=0;j<gridSize;j++)
{
if(i%2==0)
{
if(j%2==0)
{
rowString += " "
}
else
{
rowString += "#"
}
}
else
{
if(j%2==0)
{
rowString += "#"
}
else
{
rowString += " "
}
}
}
console.log(rowString);
}
}
`