0

Can anyone tell me how to solv this problem please:

I tried doing this with array.map, array.filter, array.reduce but i did not got result:

Write a function putNum(arrayOfNum: number[], num: number), which would find all possible combinations of numbers from arrayOfNum, whose sum is equal to number. Wherein:

  1. arrayOfNum contains only unique positive numbers (>0)
  2. there should not be repetitions of numbers in the combination
  3. all combinations must be unique

@param arrayOfNum: number[]

@param num: number[]

@return Array<Array<number>>

function putNum(arrayOfNum, num) {
    ***// write code only inside this function***  
    return [[1, 2], [3]];
}

// console.log(putNum([8, 2, 3, 4, 6, 7, 1], 99)); => []

// console.log(putNum([8, 2, 3, 4, 6, 7, 1], 5)); => [[2, 3], [4, 1]]

// console.log(putNum([1, 2, 3, 4, 5, 6, 7, 8], 8)); => [[1, 3, 4], [1, 2, 5], [3, 5], [2, 6], [1, 7], [8]]

let resultnum = result.filter(e => typeof e === 'number' && e > 0); // to make a new array with nums > 0
Shadlia
  • 1
  • 2
  • 1
    looks like this: https://stackoverflow.com/questions/53659151/return-all-subsets-whose-sum-is-a-given-value-subset-sum-problem/53659385#53659385 – Nina Scholz Jan 12 '23 at 09:52
  • 1
    Is this an interview question or homework? Please refer to [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Hao Wu Jan 12 '23 at 09:52
  • Have you already tried something that you could show ? – challet Jan 15 '23 at 10:39
  • Does this answer your question? [Return all subsets whose sum is a given value (subset sum problem)](https://stackoverflow.com/questions/53659151/return-all-subsets-whose-sum-is-a-given-value-subset-sum-problem) – jdsurya Jan 17 '23 at 06:56

1 Answers1

0

The best approach to solve this problem in optimized way is to use hash map

    let twoSum = (array, sum) => {
    let hashMap = {},
      results = []

        for (let i = 0; i < array.length; i++){
            if (hashMap[array[i]]){
                results.push([hashMap[array[i]], array[i]])
            }else{
                hashMap[sum - array[i]] = array[i];
            }
          }
          return results;
    }
console.log(twoSum([10,20,40,50,60,70,30],50));

Output:

[ [ 10, 40 ], [ 20, 30 ] ]
Ali Iqbal
  • 344
  • 1
  • 6