Advertisement
Guest User

Untitled

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