Created
February 12, 2013 00:32
-
-
Save elicwhite/4758988 to your computer and use it in GitHub Desktop.
Difference between integers = k
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
/*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