Skip to content

Instantly share code, notes, and snippets.

@maxcap
Last active February 27, 2019 13:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxcap/61cc2666044b0f20da09 to your computer and use it in GitHub Desktop.
Save maxcap/61cc2666044b0f20da09 to your computer and use it in GitHub Desktop.
Eloquent Javascript Book: Exercise Answers
/*
These are my attempts at the exercises in the book Eloquent Javascript
http://eloquentjavascript.net
*/
var size = 8;
for (var row = 1; row <= size; row++) {
var line = "";
for (var col = 1; col <= size; col++) {
// Key to this problem is adding up the row number and col number of a particular square.
if ((row + col) % 2 === 0) {
line += " ";
} else {
line += "#";
}
}
console.log(line);
}
/*
Question at http://eloquentjavascript.net/02_program_structure.html
*/
for (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);
}
}
/*
Write a loop that makes seven calls to console.log to output the
following triangle:
#
##
###
####
#####
######
#######
*/
var line = "";
for (var i = 0; i < 7; i++) {
line += "#";
console.log(line);
}
function min(x, y) {
if (x <= y) {
return x;
} else {
return y;
}
}
function isEven(x) {
// Convert any negative integers to positive
if (x < 0) {
x *= x;
}
if (x === 0) {
return true;
} else if (x === 1) {
return false;
} else {
return isEven(x - 2);
}
}
// Is "string" an acceptable parameter name?
function countBs(string) {
var numBees = 0;
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) === "B") {
numBees += 1;
}
}
return numBees;
}
function countChar(string, char) {
var numChars = 0;
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) === char) {
numChars += 1;
}
}
return numChars;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment