OUED
OUED

Reputation: 31

find sum from list of array values

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]

Upvotes: 1

Views: 93

Answers (2)

YJR
YJR

Reputation: 1202

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

Upvotes: 0

sachin
sachin

Reputation: 1117

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..

Upvotes: 1

Related Questions