Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to find all possible combinations of numbers from an array that equal to N in JavaScript

1 Answer

0 votes
function GetCombinationsEqualToN(arr, N, combination) {
    let sum = 0;
    
    for (const num of combination) {
        sum += num;
    }
        
    if (sum == N) {
        console.log("sum(" + combination.join(" ").toString() + ") = " + N);
    }
    
    if (sum >= N) {
        return;
    }
    
    for (let i = 0; i < arr.length; i++) {
        let remaining = []; 
        for (let j = i + 1; j < arr.length; j++) {
            remaining.push(arr[j]);
        }
        
        let combination_next = Array.from(combination);
        combination_next.push(arr[i]);
        
        GetCombinationsEqualToN(remaining, N, combination_next);
    }
}

const arr = [4, 6, 8, 2, 1, 10, 3, 5, 13];
const N = 13;

GetCombinationsEqualToN(arr, N, []);





/*
run:

"sum(4 6 2 1) = 13"
"sum(4 6 3) = 13"
"sum(4 8 1) = 13"
"sum(4 1 3 5) = 13"
"sum(6 2 5) = 13"
"sum(8 2 3) = 13"
"sum(8 5) = 13"
"sum(2 1 10) = 13"
"sum(10 3) = 13"
"sum(13) = 13"

*/

 



answered Oct 15, 2022 by avibootz
...