Skip to content

Instantly share code, notes, and snippets.

@kylebakerio
Last active August 29, 2015 14:14
Show Gist options
  • Save kylebakerio/aaa61b66c1b1693daa3c to your computer and use it in GitHub Desktop.
Save kylebakerio/aaa61b66c1b1693daa3c to your computer and use it in GitHub Desktop.
return the smallest positive difference between elements of an array of numbers
var findSmallestDifference = function(arr) {
var differences = [];
arr.sort(function(c,d){return c - d});
for(a=0;a<arr.length;a++){
for(b=a+1;b<arr.length;b++){
differences[differences.length] = arr[b] - arr[a];
}
}
var answer = (differences[0]*2)
for (e=0;e<differences.length;e++){
if (differences[e] < differences[e+1]) {
var bestOfTwo = differences[e]
if (bestOfTwo < answer) {
answer = bestOfTwo;
}
}
}
return answer;
};
var result = findSmallestDifference([102,10,-1,-6,1000,291892,]);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment