Last active
August 29, 2015 14:14
-
-
Save kylebakerio/aaa61b66c1b1693daa3c to your computer and use it in GitHub Desktop.
return the smallest positive difference between elements of an array of numbers
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
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