JavaScript

jsHike Exercises and Solutions

By October 28, 2016 No Comments

Hi again! I am going to do the exercises in the book again but this time share my solutions with you. This time the hike will be a bit more relaxed, I will try to do one exercise per day but I might take a break from time to time, especially as it is almost Christmas and I will definitely be taking a few days off for that to spend some time with my family 🙂

So let’s get started. Again these are my solutions and they are not the same one as in the Eloquent JavaScript book.

Feel free to comment your own solutions, but be careful when doing so because post codes in the comment section can be terribly annoying (thanks wordpress…) wrap your code in code tags like this:

<code>I am code</code>

Off we go!

Chapter 2: Program Structure
Exercise 1: Looping a triangle
Exercise 2: FizzBuzz
Exercise 3: Chess Board
Chapter 3: Functions
Exercise 1: Minimum
Exercise 2: Recursion
Exercise 2: Bean counting

Exercises

Chapter 2: Program Structure

Exercise 1: Looping a triangle

Write a loop that makes seven calls to console.log to output the following triangle:

var line = "#";
for (line = "#"; line.length < 8; line += "#")
  console.log(line);

To check the result open up devTools on your browser and run it.

Exercise 2: 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).

var number;

for (number =1; number <= 100; number++) {

    if (number % 3 ==0 & number % 5 ==0) {
        console.log('fizzbuzz');
    } else if (number % 3 == 0) {
        console.log('fizz');
    } else if (number % 5 == 0) {
        console.log('buzz')
    } else {
        console.log(number);
    }

}

Exercise 3: 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.

var size = 8; 

var board = "";
for (var y = 0; y < size; y++) {   // in the outer loop we add newline to separate rows
  for (var x = 0; x < size; x++) {// every inner loop represents a line, and alternatively it's adding either ' ' or '#' to the string that's being populated

    if ((x + y) % 2 == 0)
      board += " ";
    else
      board += "#";
  }
  board += "\n";
}

console.log(board);

Chapter 3: Functions

Exercise 1: Minimum

The previous chapter introduced the standard function Math.min that returns its smallest argument. We can do that ourselves now. Write a function min that takes two arguments and returns their minimum.

function minimum(a, b) {
  if (a < b)
    return a;
  else
    return b;
}

Exercise 2: Recursion

We’ve seen that % (the remainder operator) can be used to test whether a number is even or odd by using % 2 to check whether it’s divisible by two. Here’s another way to define whether a positive whole number is even or odd:

Zero is even.

One is odd.

For any other number N, its evenness is the same as N - 2.

Define a recursive function isEven corresponding to this description. The function should accept a number parameter and return a Boolean.

Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a way to fix this?

function isEven(number) {
  if (number < 0) {
    number = Math.abs(number);
  }
  if (number===0) {
    return true;
  }
  if (number===1) {
    return false;
  }
  else {
    number = number - 2;
    return isEven(number);
  }

}

Exercise 3: Bean counting

You can get the Nth character, or letter, from a string by writing "string".charAt(N), similar to how you get its length with "s".length. The returned value will be a string containing only one character (for example, "b"). The first character has position zero, which causes the last one to be found at position string.length - 1. In other words, a two-character string has length 2, and its characters have positions 0 and 1.

Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters are in the string.

Next, write a function called countChar that behaves like countBs, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function.

function countBs(str){
  var num = 0;
 
  for(var i = 0; i < str.length; i += 1){
    if(str[i] === 'B'){
      num += 1;
    }
  }
  return num;
}
function countChar(str, letter){
  var num = 0;
 
  for(var i = 0; i < str.length; i += 1){
    if(str[i] === letter){
      num += 1;
    }
  }
  return num;
}


function countBs(str){
  return countChar(str, 'B');
}
 
function countChar(str, letter){
  var num = 0;
 
  for(var i = 0; i < str.length; i += 1){
    if(str[i] === letter){
      num += 1;
    }
  }
  return num;
}

Leave a Reply