Skip to content

Instantly share code, notes, and snippets.

@a1ip
Last active June 25, 2019 15:12
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save a1ip/ac95742bf7ae0175b3fb to your computer and use it in GitHub Desktop.
Save a1ip/ac95742bf7ae0175b3fb to your computer and use it in GitHub Desktop.
Solutions for Exercises from Eloquent Javascript http://eloquentjavascript.net/
// Looping a triangle
// http://eloquentjavascript.net/2nd_edition/preview/02_program_structure.html
var s = '';
for (var i=1;i<=7;i++){
s += '#';
console.log(s);
}
// FizzBuzz
// http://eloquentjavascript.net/2nd_edition/preview/02_program_structure.html
for (var i=1; i<=100; i++) {
if (i % 15 === 0)
console.log('FizzBuzz');
else if (i % 3 === 0)
console.log('Fizz');
else if (i % 5 === 0)
console.log('Buzz');
else
console.log(i);
}
// Chess board
// http://eloquentjavascript.net/2nd_edition/preview/02_program_structure.html
var size = 8;
for (var i = 0; i < size; i++) {
var s='';
for (var j = 0; j < size; j++) {
if ((i+j)%2 === 0) {s += '#';} else {s += ' ';}
}
console.log(s);
}

http://eloquentjavascript.net/2nd_edition/preview/03_functions.html
Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. How would you write a function that, given a number, tries to find a sequence of such additions and multiplications that produce that number? For example, the number 13 could be reached by first multiplying by 3 and then adding 5 twice, whereas the number 15 cannot be reached at all.

Here is a recursive CoffeeScript solution:

findSolution = (target) ->
  find = (start, history) ->
    if start is target
      history
    else if start > target
      null
    else
      find(start + 5, "(#{history} + 5)") or find(start * 3, "(#{history} * 3)")
  find 1, "1"
console.log findSolution(24)
// Minimum
// http://eloquentjavascript.net/2nd_edition/preview/03_functions.html
function min(x, y) {
return x < y ? x : y
}
// Recursion
// http://eloquentjavascript.net/2nd_edition/preview/03_functions.html
function isEven(n) {
if (n === 0) {
return true;
} else if (n === 1) {
return false;
} else {
return n > 0 ? isEven(n-2) : isEven(n+2);
}
}

####Recursion

http://eloquentjavascript.net/2nd_edition/preview/03_functions.html
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?

isEven = (n) ->
  if n is 0
    true
  else if n is 1
    false
  else
    (if n > 0 then isEven(n - 2) else isEven(n + 2))
// Bean counting
// http://eloquentjavascript.net/2nd_edition/preview/03_functions.html
function countBs(str) {
return countChar(str, 'B');
}
function countChar(str, chr) {
var counter = 0
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) === chr) {counter++;}
}
return counter;
}

####Bean counting

http://eloquentjavascript.net/2nd_edition/preview/03_functions.html
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.

countBs = (str) ->
  countChar str, "B"

countChar = (str, chr) ->
  counter = 0
  for i in [0...str.length]
    counter++ if str.charAt(i) is chr
  counter
// The sum of a range
// http://eloquentjavascript.net/2nd_edition/preview/04_data.html
function range(start, end, step) {
if (!step) { step = 1; }
var r = [];
for (var i = start; start <= end ? i <= end : i >= end; i += step) { r.push(i); }
return r;
}
function sum(arr) {
var s = 0;
for (var i = 0; i < arr.length; i++) { s += arr[i];}
return s;
}

####The sum of a range

The introduction of this book alluded to the following as a nice way to compute the sum of a range of numbers:

console.log(sum(range(1, 10)))

Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.

Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.

As a bonus assignment, modify your range function to take an optional third argument that indicates the “step” value used to build up the array. If no step is given, the array elements go up by increments of one, corresponding to the old behavior. The function call range(1, 10, 2) should return [1, 3, 5, 7, 9]. Make sure it also works with negative step values so that range(5, 2, -1) produces [5, 4, 3, 2].

range = (start, end, step) ->
  step = 1  unless step
  r = []
  i = start

  while (if start <= end then i <= end else i >= end)
    r.push i
    i += step
  r

sum = (arr) ->
  s = 0
  for i in arr
    s += i
  s
@vulchivijay
Copy link

vulchivijay commented Jun 14, 2017

Hi,

example: eloquentjavascript-04-01.js
It is killing browser because there is no stop in loop, loop is repeating infinity times.

for (var i = start; start <= end ? i <= end : i >= end; i += step) { r.push(i); }
return r;
}

problem in start <= end ? i <= end : i >= end; i += step. please check it.

I have written like this.

function range(start, end, step) {
var myArray = [];
if (!step) {
step = 1;
}
if(start <= end) {
for(start; start<=end; start++) {
myArray.push(start);
}
}
else {
for(start; start>=end; start--) {
myArray.push(start);
}
}
console.log(myArray);
sum(myArray);
}
function sum(myArray) {
var sumOf = 0;
for(var i=0; i<myArray.length; i++){
sumOf = sumOf + myArray[i];
}
console.log("Array total is: " + sumOf);
}
range(1,10);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// Array total is: 55
range(10,1);
// [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
// Array total is: 55
range(-1,5);
// [-1, 0, 1, 2, 3, 4, 5]
// Array total is: 14

@enigmatikme
Copy link

// Your code here.
function range(start, end, step) {
var arr = [];
if (!(step)) {
step = 1;
}
if (step < 1) {
if (end < start) {
for (var i = start; i >= end; i--) {
arr.push(i);
}
}
}
if (step >= 1) {
for (var i = start; i <= end; i++) {
arr.push(i);
}
}
return arr;
}

function sum(argument) {
var arr = argument;
return arr.reduce(function(acc, num) {
return acc += num;
},0);
}
//console.log(range(1, 10, 2));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// → 55

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment