Created
December 2, 2020 23:57
-
-
Save ubershmekel/c38bb570b57dfc997b0f7d8777bcc549 to your computer and use it in GitHub Desktop.
From 2020-11-29 [email protected] newsletter challenge Given an array of integers and a target value, return the number of pairs of array elements that have a difference equal to a target value.
This file contains hidden or 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
/* | |
From 2020-11-29 [email protected] newsletter challenge | |
Given an array of integers and a target value, return the number of pairs of array | |
elements that have a difference equal to a target value. | |
Examples: | |
$ arrayDiff([1, 2, 3, 4], 1) | |
$ 3 // 2 - 1 = 1, 3 - 2 = 1, and 4 - 3 = 1 | |
*/ | |
function arrayDiffBrute(arr, target) { | |
let pairCount = 0; | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = i + 1; j < arr.length; j++) { | |
if (Math.abs(arr[i] - arr[j]) === target) { | |
pairCount++; | |
} | |
} | |
} | |
return pairCount; | |
} | |
function arrayDiff(arr, target) { | |
let pairCount = 0; | |
let valToIndex = {}; | |
for (let i = 0; i < arr.length; i++) { | |
if (!valToIndex[arr[i]]) { | |
valToIndex[arr[i]] = [] | |
} | |
valToIndex[arr[i]].push(i); | |
} | |
for (let i = 0; i < arr.length; i++) { | |
diffTarget = arr[i] + target; | |
if (valToIndex[diffTarget]) { | |
pairCount += valToIndex[diffTarget].length; | |
} | |
} | |
return pairCount; | |
} | |
const tests = [ | |
{ | |
arr: [1, 2, 3, 4], | |
target: 1, | |
expected: 3, | |
}, | |
{ | |
arr: [1, 4], | |
target: 1, | |
expected: 0, | |
}, | |
{ | |
arr: [1, 4], | |
target: 3, | |
expected: 1, | |
}, | |
{ | |
arr: [1, 4, 9, 14], | |
target: 5, | |
expected: 2, | |
}, | |
]; | |
for (const test of tests) { | |
const result = arrayDiff(test.arr, test.target); | |
console.log(`arr: ${test.arr}, expected: ${test.expected}, got: ${result}`); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment