Created
June 3, 2016 02:34
-
-
Save jjhampton/54bb51677ff58ad0324cd5cb2e531f92 to your computer and use it in GitHub Desktop.
Solutions to the exercises from Chapter 2 of Eloquent JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
// Looping a Triangle | |
// Write a loop that makes seven calls to console.log to output the following triangle: | |
// # | |
// ## | |
// ### | |
// #### | |
// ##### | |
// ###### | |
// ####### | |
for (let outputCharacter = '#'; outputCharacter.length < 8; outputCharacter += '#') { | |
console.log(outputCharacter); | |
} | |
// FizzBuzz | |
// Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. | |
// When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those). | |
for (let number = 1; number < 101; number++) { | |
let text = ''; | |
let isDivisibleBy3 = number % 3 === 0; | |
let isDivisibleBy5 = number % 5 === 0; | |
if (isDivisibleBy3) | |
text += 'Fizz'; | |
if (isDivisibleBy5) | |
text += 'Buzz'; | |
console.log(text || number); // outputs a Fizz/Buzz/FizzBuzz string, or if text is empty, outputs the number | |
} | |
// Chess board | |
// Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board. | |
// Passing this string to console.log should show something like this: | |
// # # # # | |
// # # # # | |
// # # # # | |
// # # # # | |
// # # # # | |
// # # # # | |
// # # # # | |
// # # # # | |
// When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height. | |
const size = 8; // this can be changed to any size grid | |
let string = ''; | |
for (let i = 0; i < size; i++) { | |
for (let j = 0; j <= size; j ++) { | |
if (j === size) { | |
string += '\n'; | |
break; | |
} | |
let character = i + j; // toggles the output character on even/odd lines | |
if (character % 2 === 0) | |
string += ' '; | |
else | |
string += '#'; | |
} | |
} | |
console.log(string); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment