Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. //Robin Coding Challenge!
  2.  
  3.  
  4. //Write a function in JavaScript that accepts an array of integers and a number X as parameters, when invoked, returns an array of unique indices of two numbers whose sum is equal to X.
  5.  
  6. // For example: [1, 3, 4, 5, 6, 8, 10, 11, 13], Sum: 14
  7.  
  8. // Pairs of indices: [0, 8], [1, 7], [2, 6], [4, 5]
  9.  
  10.  
  11.  
  12. //define variables:
  13. const numbers = [1, 3, 4, 5, 6, 8, 10, 11, 13]
  14. const sum = 14
  15.  
  16. //Create function with two arguments (array, sum)
  17. //Create variable to return independent index pairs
  18.  
  19. findSum = (array, x) => {
  20. var indexArr = []
  21.  
  22. //For loop, iterating over all numbers in the set, searching for the difference between X (sum) and value at each index
  23. //Lists indices of numbers whose sums total X, pushes to empty array
  24.  
  25. for(let i = 0; i <= array.length; i++) {
  26. var map = array[i]
  27. var diff = (x - map)
  28. var index = array.indexOf(diff)
  29. var answer = [i, index]
  30. if (index > i) {
  31. indexArr.push(answer)
  32. }
  33. } return indexArr
  34. }
  35. console.log(findSum(numbers, sum));
  36.  
  37.  
  38. //This solution is a bit blunt force, with the discriminating if statement working because each array value is sequential
  39. //I would refactor to discriminate between index values and that were already listed, even if the number set given was not sequential
  40. //I might also consider using .reduce() with the list of indices as an accumulator
  41. //I would love to hear your notes on this, thank you for your consideration! -Chris
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement