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)
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