Created
October 18, 2019 16:29
-
-
Save tianmingzuo/8fa6aa71df590b59981f09abd741478c to your computer and use it in GitHub Desktop.
Pairwise: Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices. You may use multiple pairs that have the same numeric elements but different indices. Each pair should use the lowest possible available indices. Once an element has been used it cannot be reused to pair with another elem…
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
| function pairwise(arr, arg) { | |
| let sum = 0; | |
| for(let i=0; i<arr.length-1; i++){ | |
| for(let j=i+1; j<arr.length; j++){ | |
| if(arr[i] + arr[j] === arg){ | |
| sum += (i+j); | |
| arr[i] = arg + 1; // to avoid the arr[i] being reused | |
| arr[j] = arg + 1; // to avoid the arr[j] being reused | |
| } | |
| } | |
| } | |
| return sum; | |
| } | |
| pairwise([1,4,2,3,0,5], 7); // return 11 | |
| /* | |
| pairwise([1, 3, 2, 4], 4) should return 1. | |
| Passed | |
| pairwise([1, 1, 1], 2) should return 1. | |
| Passed | |
| pairwise([0, 0, 0, 0, 1, 1], 1) should return 10. | |
| Passed | |
| pairwise([], 100) should return 0. | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment