-6

Input

 Array =[4,2,8,11,14,6,1]
     Expectedtotal=20

Output

[2,4,6,8], [11,8,1],[6,11,1,2],[2,14,4],[14,6]

code:

const arr = [4, 2, 8, 11, 14, 6, 1];
const target = 20;
res = _.filter(arr, v => _.filter(arr, v1 => _.filter(arr, v2 => _.filter(arr, v3 => v + v1 + v2 + v3 === target))); console.log(res);

I am the beginner of javascript and lodash. I tried this code by own..please help me to write good code.

User863
  • 19,346
  • 2
  • 17
  • 41
  • 2
    What have you tried so far? I don't know if you are quizzing or asking how to get the expected output. Please edit/update your post with the relevant source code **[Your attempt(s)]** Thank you. – NewToJS Jan 11 '19 at 10:32
  • 2
    You're using Stack Overflow wrong. We dont do your homework for you. Your problem is thta you dont know how to do it from a logical point of view, not a practical one. Show your work and tell us errors you get. – Simon Hyll Jan 11 '19 at 10:32
  • What did you try? – ellipsis Jan 11 '19 at 10:37

1 Answers1

3

You could use a temporary array and the index and iterate the next index by either taking the actual value or not.

function subsetSum(array, sum) {

    function iter(index, temp, s) {
        if (s === sum) return result.push(temp.slice());              // exit sum found
        if (index >= array.length) return;                            // exit index over
        iter(index + 1, temp.concat(array[index]), s + array[index]); // take value
        iter(index + 1, temp, s);                                     // omit value
    }

    var result = [];
    iter(0, [], 0);
    return result;
}

console.log(subsetSum([4, 2, 8, 11, 14, 6, 1], 20).map(a => a.join(' ')));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392