How can I get number of combinations with given sum?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
For example in vector [3,2,2,2,1,1,1,1,1] and given sum 4 the result should be counted like
- 5 choose 4 possibilities to choose 4 ones (1+1+1+1=4)
- (3 choose 1)*(5 choose 2) possibilities to choose 1 two and 2 ones (2+1+1=4)
- 3 choose 2 possibilities to choose 2 twos (2+2=4)
- (1 choose 1)*(5 choose 1) possibilities to choose 1 three and 1 one (3+1=4)
So the number of combinations is (5 choose 4)+(3 choose 1)*(5 choose 2)+(3 choose 2)+(1 choose 1)*(5 choose 1)=5+3*10+3+1*5=43 if I didn't do any mistake.
But I don't know how to write this algorithm to matlab so I use brute force and just generate all combinations with one element, then all combinations with two elements etc. and then for all combinations find ouf if their sum is equal to given number. So in these comninations are for example 30 combinations [2,1,1]. But I want faster algorithm which find only one time combination [1,1,1,1] and then use nchoosek to count, how many possibilities are there to get 4 ones of 5. Then find [2,1,1] and count again number of possibilities (30) etc. Can anyone help me?
0 commentaires
Réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!