1

I have this script that give all possible combinations from the given array.

I want to make the same thing but use each element only once.

        const arr = [144, 35, 20, 10];
        const sum = 65;
        const findSum = (arr, sum) => {
            const res = [];
            const search = (index, part = []) => {
                const s = part.reduce((a, b) => a + b, 0);
                if (s === sum) {
                    res.push(part)
                };
                if (s >= sum || index >= arr.length) { return; };
                search(index, part.concat(arr[index]));
                search(index + 1, part);
            };
            search(0);
            return res;
        }
        console.log(findSum(arr, sum));

the output for this example gives two combinations 0: [35, 20, 10] 1: [35, 10, 10, 10]

so i need avoid is an element multiple times like for value 10

that will give only one possible combination [35, 20, 10]

1
  • something is wrong, if I const sum = 179 it calls search() 530 times... jsfiddle.net/g94e3L5d Commented Oct 1, 2022 at 12:04

2 Answers 2

1

The quick fix for your solution would be like this :

    const arr = [144, 35, 20, 10];
    const sum = 65;
    const findSum = (arr, sum) => {
        const res = [];
        const search = (index, part = []) => {
            const s = part.reduce((a, b) => a + b, 0);
            if (s === sum) {
                res.push(part)
            };
            if (s >= sum || index >= arr.length) { return; };
            search(index, part.concat(arr[index]));
            search(index + 1, part);
        };
        search(0);
        return res;
    }
    console.log(findSum(arr, sum).filter(d => d.length == [...new Set(d)].length));

Hope this helps you!
Comment if you get any doubts here..

Sign up to request clarification or add additional context in comments.

2 Comments

something is still wrong: jsfiddle.net/5h0jnz9u why search() is called 530 times?
Hey look at the last line... ( console.log ) that's the only change I did. That will be the quick fix. You have to change the code logic if you want to completely change it.
0

You can achieve expected result by changing search(index, part.concat(arr[index])); to this search(index+1, part.concat(arr[index]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.