So i wanted to take my time to really make sure i understand these exercises before posting my answers here, since the first answer was given to us by Ivan, and the third was so impossible for me to wrap my head around i actually had to look up the answer here in the forum, as well as looking up the Eloquent JavaScript solution. But now that i finally understand whats what, i think i’m ready to move on. (That and the fact that i already worked through chapter 3 as well as those exercises as well. Like, its long past time.
)
So, for the first exercise, The Eloquent JavaScript solution is by far the most efficient way to solve this with the least amount of code. It simply uses a single for loop to generate the triangle, and by the textbook examples i had seen so far in the book, it's was also the most creative way I've seen the for loop be used. It immediately starts by defining a variable to be an empty string value, then uses the .length property of said string to keep track of the loops condition, and then increases the string value by a "#" for each iteration of the loop. The loop's code block contains one simple line of code, console.log(string) which makes sure that the loop generates the triangle in the console, one line at a time.
The code for this would be as follows:
for (let string = "" ; string.length < 8 ; string += "#") {
console.log(string);
}
For the second exercise, FizzBuzz, i actually thought this exercise was so easy that i actually solved in the very first attempt as soon as i came upon it. I don’t mean to brag though, i’m sure this is child’s play to someone else reading this, but to me it was super exiting to just write some code and it works straight away. Anyway, since i learned about functions before writing this, i decided to embed my code into a function, just for fun.
function fizzbuzz(number) {
for (let counter = 1 ; counter <= number ; counter++) {
if (counter % 3 == 0 && counter % 5 == 0) {
console.log("FizzBuzz");
continue;
}
else if (counter % 3 == 0) {
console.log("Fizz");
continue;
}
else if (counter % 5 == 0) {
console.log("Buzz");
continue;
}
else {
console.log(counter);
}
}
}
fizzbuzz(number);
Now i don’t know if i really need to explain what goes on here as it’s pretty straight forward.
I use the modulus/remainder operator (%
) in an if / else if chain. In the first one it checks if the number held in counter is evenly divisible by both 3 and (&&
) 5.
If it is converted to true, “FizzBuzz” is printed out and the keyword continue;
alters the control flow so that the rest of the code doesn’t run and instead continues with the for
-loop’s next iteration. If the first check isn’t converted to true, then it proceeds to the other two checks who tests if counter is evenly divisible with first 3, and then 5. (respectively)
If either check is true, it prints Fizz or Buzz (respectively). If neither of the checks converts to true, then it simply prints out the number held by counter
. And lastly, since i made it into a function. You can simply call it by writing fizzbuzz(number)
, where number
is the parameter where you pass your argument of how high you want the function to test. This way you could insert any number (unless it’s so high and your machine runs out of memory and crashes). So basically, this function is a way to test which numbers are evenly divisible with 3, 5, or both. From 1 all the way to a number of your choosing.
-
Chessboard
Aight so this exercise kinda made me wish i had hair just so i could pull it out.
I had to look it up eventually, even though i really don’t like “cheating” in these exercises, i felt like there was no way i could figure it out on my own. But i guess the point if these exercises isn’t prestige or pride but actually understanding them. I think i do now though.
Also, since a point in this exercise is scalability, i decided to also make it a function.
So here is my code before i go on to explain it:
function chessboard(size) {
let string = ""
for (let height = 0 ; height < size ; height++) {
for (let width = 0 ; width < size ; width++) {
if ((width + height) % 2 == 0) {
string += " "
} else {
string += "#"
}
}
string += "\n"
}
console.log(string);
}
chessboard(8)
So, for the sake of scalability and user-friendliness i made it into a function that you simply call by typing chessboard(size);
where size is the parameter where you pass your argument for how big you want the chessboard to be.
So chessboard(8);
for example, generates an 8x8 grid.
What the function body does first is that it defines the variable string
to simply be an empty string value. It is then followed by a loop containing yet another loop. The variables in the textbook examples are originally named x
and y
but i thought it would be easier to name them height
and width
, the reason that we use two loops like this is because the function works two angles.
The first for
loop keeps track of the number of lines by starting with 0, and incrementing by 1 for each iteration of the loop, as long as it is less than the parameter size
(that you pass your numeric argument into when you first call the function).
Now, since the first loop’s body contains yet another loop, after the first iteration of the outer loop, control goes into the inner loop. This loop handles the width of the chessboard, or rather, the characters on each line.
It does this just like the first loop, it starts from 0, incrementing by one while its value is less than the size (that you gave it) - however, after each iteration of its loop, it proceeds to the code block contained within it - and this is where the magic happens.
The if statement that follows compares the sum of the values contained in height
and width
, and uses the modulus operator (%
) to determine if the remainder of this sum is 0 when divided by 2.
-
If this is converted to true, the empty string value contained in the variable string
gets updated (concatenated) with a blank space " "
,
-
If the statement is converted to false (the sum of height and width isn’t evenly divisible by 2, = the sum is an odd number), the variable string instead gets updated (concatenated) with a hashtag “#”.
Once the code inside the inner loop has run its first time, the loop yet again increments its value width
with one, and once again runs the if statement. This is the code that decides whether a blank space, or a hashtag should be concatenated next to the once-empty string in the beginning of the function body. The way control flow works makes sure that the inner loop runs all the way up until it has generated one entire line of the chessboard (until the width
variable is no longer < size
), before control proceeds out of the loop.
However, there is one last stop before control comes back to the outer loop. The cleverly added newline character (\n
), or rather, the concatenation of a newline character into the very same string
that the inner loop was just working on. This, together with the first (outer) loop is what makes sure that the chessboard string
that is later printed out at the very end of the function is nicely and evenly cut up into size
-number of times.
When control flow once again comes back to the first for
-statement to iterate its second loop, the height
variable is incremented by one, so when the inner function, with the help of its if
-statement, then starts to cycle through width
and test which character to add next chessboard string
- It does the exact same thing again, except producing the “opposite result” each time. The first iteration started with an even sum (height + width)
. The second time however, since height
is increased by one, the second iteration now starts with an odd sum.
This is what makes it so that the chessboard alternates the layout of the hashtags and spaces.
The function does this over and over, generating line after line, separated with a newline character. And only once both loops have run until their respective courses and no longer meets the condition (
variable < size)
. The program finally prints out the now fully generated single string, consisting of hashtags, spaces and newline characters, representing a chessboard.
Sorry for wall of text. I guess i understand it now though. 