Keep It Simple, Stupid | |
PerlMonks |
Re: Faster alternative to Math::Combinatoricsby Laurent_R (Canon) |
on Sep 02, 2017 at 11:40 UTC ( [id://1198575]=note: print w/replies, xml ) | Need Help?? |
Hi AppleFritter,
you've already received good solutions for your problem, but I thought it might be beneficial to provide a basic algorithm to solve it. This is using recursion. (I know I'm coming a bit late, but I did not have time yesterday to code and test anything.) Anyway, this is my (first) solution: If I run this, I get the following (abbreviated) output:
So, this is pretty fast. Now, there is a slight problem. This program is not producing the same results as those you appear to be expecting (I am not talking about the different formatting, but about the number and list of results). For example, looking only at the weight of 3, I get this: whereas you seem to be expecting: I get 27 combinations and you seem to be expecting only 10. I don't understand, for example, why you have only one result starting with 2, why you don't have (2,0,0), (2,0,2), (2,0,3), (2,2,0), ... and so on. I would expect you to be willing to have all the possible combinations with repetitions (i.e. 3 ** 3 = 27 combinations), but that doesn't appear to be what you're after. Or is there an error in your expected result? Or did I miss part of your explanation? I'll make another post with a modified program which appears to produce something closer to what you seem to be expecting. Update: Modified the list of "missing" combinations listed just above to reflect the input data (O, 2, 3 and not 0, 1, 2).
In Section
Seekers of Perl Wisdom
|
|