Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Robin Coding Challenge!
- //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.
- // For example: [1, 3, 4, 5, 6, 8, 10, 11, 13], Sum: 14
- // Pairs of indices: [0, 8], [1, 7], [2, 6], [4, 5]
- //define variables:
- const numbers = [1, 3, 4, 5, 6, 8, 10, 11, 13]
- const sum = 14
- //Create function with two arguments (array, sum)
- //Create variable to return independent index pairs
- findSum = (array, x) => {
- var indexArr = []
- //For loop, iterating over all numbers in the set, searching for the difference between X (sum) and value at each index
- //Lists indices of numbers whose sums total X, pushes to empty array
- for(let i = 0; i <= array.length; i++) {
- var map = array[i]
- var diff = (x - map)
- var index = array.indexOf(diff)
- var answer = [i, index]
- if (index > i) {
- indexArr.push(answer)
- }
- } return indexArr
- }
- console.log(findSum(numbers, sum));
- //This solution is a bit blunt force, with the discriminating if statement working because each array value is sequential
- //I would refactor to discriminate between index values and that were already listed, even if the number set given was not sequential
- //I might also consider using .reduce() with the list of indices as an accumulator
- //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