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