Created
July 11, 2017 09:04
-
-
Save kevindekemele/ef19f1ab364ef5a0e66187275ed41b61 to your computer and use it in GitHub Desktop.
Calculates the backward difference of an array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function factorial(x) { | |
if(x ===0) return 1; | |
return x === 1 || x ===0 ? x : x * factorial(x - 1) ; | |
} | |
function binomial (n, k) { | |
if (!Number.isInteger(n) || !Number.isInteger(k)) { | |
return false; | |
} | |
return factorial(n) / (factorial(k) * factorial(n-k)); | |
} | |
function nThDifference(array, n){ | |
if (!Number.isInteger(n)) { | |
return false; | |
} | |
// Check if inputs are OK | |
var difference = 0; | |
if(array.length < n+1){ | |
//Zero pad to add zeros | |
for(var i=0;i<n+1-array.length;i++){ | |
array.unshift(0); | |
} | |
} | |
for(var i=0;i<n+1;i++){ | |
console.log(array[array.length-1-i]); | |
difference = difference+ Math.pow(-1,i)*binomial(n,i)*array[array.length-i-1]; | |
} | |
return difference; | |
} | |
var a = [5.0, 5.4, 6.0, 6.8, 7.5,8.1]; | |
console.log(nThDifference(a,5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment