Faster alternative to Math::Combinatoricsby AppleFritter (Vicar)
|on Sep 01, 2017 at 13:20 UTC||Need Help??|
AppleFritter has asked for the wisdom of the Perl Monks concerning the following question:
Oh monks of the round table, who dance whene'er they're able, who dine well here in Camelot and eat ham and jam and spam a lot!
Can someone recommend a faster alternative to Math::Combinatorics, or maybe suggest a better way of doing the following?
I'm trying to generate all multisets (bags) of a specific total "weight" (let's call it w), where each element comes from a given list (of numbers, in this case), and each list element may have multiplicity 0..w in each multiset. In other words, what I'm trying to generate is a list of w-tuples of elements of the given list — but unordered tuples rather than ordered ones.
An example may be instructive. Let's say w is 4, and the list is (0, 2, 3). Then I'd like to get the following multisets:
(The order in which the multisets itself are generated isn't important to me either, BTW. I've only listed them in order for the sake of readability.)
Not wanting to implement this myself, I turned to CPAN and found Math::Combinatorics. This works, but it's fairly slow. Here's a (slightly simplified) excerpt from my code:
This produces the desired output, but it takes almost 90 seconds to run for $states = 4, and much longer for 5 and up:
90 seconds wouldn't be so bad, since this is part of a larger script to generate datafiles that only really needs to be run once (to generate the file). But I'd rather not spend days waiting for it to finish for higher values of $states.
Any suggestions? Like I said, I'd prefer to stick to CPAN, but I'll take what I can get.