Skip to content

Instantly share code, notes, and snippets.

@kevindekemele
Created July 11, 2017 09:04
Show Gist options
  • Save kevindekemele/c03e3a1a7ba975b5b36cb7b6fd617255 to your computer and use it in GitHub Desktop.
Save kevindekemele/c03e3a1a7ba975b5b36cb7b6fd617255 to your computer and use it in GitHub Desktop.
Calculates the backward difference of an array.
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