I'm working on the Rosalind problem Mortal Fibonacci Rabbits and the website keeps telling me my answer is wrong when I use my algorithm written JavaScript. When I use the same algorithm in Python I get a different (and correct) answer.
Is there something about numbers in JavaScript that give me a different answer or am making a subtle mistake in my JavaScript code?
The JavaScript solution:
function fibd(n, m) {
// Create an array of length m and set all elements to 0
var rb = new Array(m);
rb = rb.map(function(e) { return 0; });
rb[0] = 1;

for (var i = 1; i < n; i++) {
// prepend the sum of all elements from 1 to the end of the array
rb.splice(0, 0, rb.reduce(function (e, s) { return s + e; }) - rb[0]);
// Remove the final element
rb.pop();
}

// Sum up all the elements
return rb.reduce(function (e, s) { return s + e; });
}
The Python solution:
def fibd(n, m):
# Create an array of length m and set all elements to 0
rp = [0] * m
rp[0] = 1

for i in range(n-1):
# The sum of all elements from 1 the end and dropping the element
rp = [sum(rp[1:])] + rp[:-1]

return sum(rp)


View Solution