Skip to content

Instantly share code, notes, and snippets.

@kylebakerio
Last active August 29, 2015 14:13
Show Gist options
  • Save kylebakerio/e5f49adfc8aed57f1e76 to your computer and use it in GitHub Desktop.
Save kylebakerio/e5f49adfc8aed57f1e76 to your computer and use it in GitHub Desktop.
Maker Square Algorithms Challenge
/*Instructions:
Submit a solution to the following challenge:
Given an array of integers, find the smallest difference between any two elements of the array. For example:
var findSmallestDifference = function(arr) {
// Your code goes here
};
var result = findSmallestDifference([100, 500, 300, 1000, -200, 990]);
console.log(result); // The answer is 10 for this example because the difference between 1000 and 990 is 10
This code should print out 10 because the different between 1000 and 990 is 10 and there are no pairs that have a smaller difference.
---------------------------- */
var differences = [], differences2 = [], findSmallestDifference = function(arr) {
//first part creates a large array composed of the answers from subtracting every number against itself.
for(a=0;a<arr.length;a++){
for(b=a+1;b<arr.length;b++){
differences[differences.length] = arr[a] - arr[b];
differences[differences.length] = arr[b] - arr[a];
}
};
//second part ignores negative numbers and adds only positive numbers into a new array, differences2.
for (c=0;c<differences.length;c++){
if (differences[c] < 0) {}
else {
differences2[differences2.length] = differences[c];
}
};
//this variable gives me a number that I can guarantee will be larger than the answer.
var answer = (differences2[0] + differences2[1])
//this part compares two numbers from differences2 at a time, saves the smaller one into a temporary variable(bestOfTwo), and then compares the smaller one against the smallest one found yet('answer', which we declated in the last line)--if 'bestOfTwo is smaller than 'answer', it replaces it; if not, it exits the loop and cycles through to repeat the process with a new set of numbers
for (d=0;d<differences2.length;d++){
if (differences2[d] < differences2[d+1]) {
var bestOfTwo = differences2[d]
if (bestOfTwo < answer) {
answer = bestOfTwo;
}
}
};
return answer;
};
var result = findSmallestDifference([100, 500, 300, 1000, -200, 990]);
console.log(result);
@taylor
Copy link

taylor commented Jan 12, 2015

Make sure it makes senses fully before re-factoring. Eg. don't condense if you do not yet comprehend what is going on.

@kylebakerio
Copy link
Author

If you add
console.log(a,b)
inside the second 'for' loop, you'll see that I'm actually not indexing 2, 2 as you suggested (I think, if I'm understanding you right).

Also, as per my comments in text, I can't seem to replicate the bug you describe. Is it because of the environment you're running the code in?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment