Created
May 26, 2020 19:33
-
-
Save jotafeldmann/e4db8f1098c449eacd2f20bcb7eb4b15 to your computer and use it in GitHub Desktop.
Write a function that: 1. Takes 2 parameters - an array of #'s and a target # 2. Return all index pairs that equal the target #
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
/* | |
Write a function that: | |
1. Takes 2 parameters - an array of #'s and a target # | |
2. Return all index pairs that equal the target # | |
3. Based on the values below the output should be | |
[[3, 5]],[1, 6]] (e.g. 2 & 7 and 5 & 4) | |
*/ | |
const nums = [1, 5, 12, 2, 3, 7, 4, 11, 15]; | |
const target = 9 | |
const getIndexPairsV2 = (list, target) => { | |
const numbersMap = {} | |
return list.map((number, index) => { | |
numbersMap[number] = index | |
const diff = numbersMap[target - number] | |
if (diff !== undefined) return [index, diff] | |
return false | |
}).filter(e => e !== false) | |
} | |
const result2 = getIndexPairsV2(nums, target) | |
console.log(result2) | |
const getIndexPairsV1 = (list, target) => { | |
const pairs = [] | |
const len = list.length | |
for(let count = 0; count <= len; count ++){ | |
let num1 = list[count] | |
for(let count2 = count + 1; count2 <= len; count2 ++){ | |
let num2 = list[count2] | |
if (num1 + num2 === target) { | |
pairs.push([count, count2]) | |
} | |
} | |
} | |
return pairs | |
} | |
const result = getIndexPairsV1(nums, target) | |
console.log(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment