Skip to content

Instantly share code, notes, and snippets.

@TheSavior
Created February 12, 2013 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheSavior/4758988 to your computer and use it in GitHub Desktop.
Save TheSavior/4758988 to your computer and use it in GitHub Desktop.
Difference between integers = k
/*Question:
Given a non-negative integer k and an array a containing random integers, determine the number of instances where two integers in the array have a numerical difference of k.
Do not assume anything about the given inputs unless it is strictly stated.
Example 1:
k = 4
a = [ 1, 1, 5, 6, 9, 16, 27]
output = 3 ( Due to 2x [1,5], and [5,9] )
Example 2:
k = 2
a = [ 1, 1, 3, 3]
output = 4 ( Due to 4x [1,3] )
CODE BELOW THE LINE, KTHX
___________________________________________________________________________
a = [3,1];
k = 2;
a = [2]
k = 0;
*/
function do (k, a) {
var counter = 0;
for (var i = 0; i < a.length; i++) {
for (var j = i+1; j < a.length; j++) {
if ((a[i] + k) == a[j] || (a[i] - k) == a[j]) { // Gotta make sure you check both directions
counter++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment