Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Function
- const indicesOfGivenSum = (arr, x) => {
- // Isolate the length of the given array
- const len = arr.length
- // Isolate the given sum 'x'
- const givenSum = x;
- // Instantiate the output varable as an empty array in which to push the appropriate indices
- let output = [];
- // Iterate over each element of the array
- for (let i = 0; i < len; i++) {
- // Compare each element of the array to every other element of the array, starting with the index after the current index 'i'
- for (let j = i + 1; j < len; j++) {
- // Placeholder for the sum of the elements are the current indices
- let currentSum = arr[i] + arr[j];
- // Compare the current sum to the given sum
- if (currentSum === givenSum) {
- // If the sum of elements at the current indices equal the given sum, push those elements as a subarray into the output array
- output.push([i, j]);
- }
- }
- }
- // Return the output array of subarrays that hold the unique indices of two numbers whose sum is equal to the given sum 'x'
- return output;
- }
- // Set variables to test the function
- const testArrOne = [1, 3, 4, 5, 6, 8, 10, 11, 13];
- const givenSumOne = 14;
- const testArrTwo = [10, 11, 12, 13, 14, 15, 16, 6, 11];
- const givenSumTwo = 22;
- const testArrThree = [1, 4, 13, 16, 7, 12, 34, 5];
- const givenSumThree = 17;
- const testArrFour = [54, 27, 3, 15, 71, 13, "The ultimate answer to life, the universe, and everything", 1, -12, -29];
- const givenSumFour = 42;
- // Test the function - I used Node.js, so I just run 'node <filename.js> from the command line to test the functionality
- console.log("Expected output: [0, 8], [1, 7], [2, 6], [4, 5]\n")
- console.log(indicesOfGivenSum(testArrOne, givenSumOne));
- console.log("\nExpected output: [0, 2], [1, 8], [6, 7]\n")
- console.log(indicesOfGivenSum(testArrTwo, givenSumTwo));
- console.log("\nExpected output: [0, 3], [1, 2], [5, 7]\n")
- console.log(indicesOfGivenSum(testArrThree, givenSumThree));
- console.log("\nExpected output: [0, 8], [1, 3], [4, 9]\n")
- console.log(indicesOfGivenSum(testArrFour, givenSumFour));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement