http://qs321.pair.com?node_id=458644


in reply to How to determine & record all possible variations for 5 items?

In the spirit of TIMTOLanguageTDI, here's a way to do it in Haskell:

partition :: Integer -> Integer -> [[Integer]] partition total 1 = [[total]] partition total numparts = concat $ map (prepend) [total, (total - 1) .. 0] where prepend x = map (x:) (subpart x) subpart x = partition (total - x) (numparts - 1) -- then: partition 100 5
Note that this will take a while, as there are over 4.5 million solutions. This doesn't take into account the "only multiples of 2 or 5" criteria, but it's easy to change it so that it does:
partition :: Integer -> Integer -> [[Integer]] partition total 1 = [[total]] partition total numparts = concat $ map (prepend) numlist where prepend x = map (x:) (subpart x) subpart x = partition (total - x) (numparts - 1) numlist = filter twoorfive [total, (total - 1) .. 0] twoorfive x = x `mod` 2 == 0 || x `mod` 5 == 0
And this gives about 600k solutions. Much more manageable.

Another way to do it would be to create all possible lists of the desired length (5 in this case), with each element in a given range (0..100 here) and filter out the ones that don't sum to 100. I tried this approach as a mind exercise (you probably wouldn't want to use it because it would be very ineffecient). I got it to work, but only by hardcoding the number of elements to five, using a list comprehension. I know this is a Perl board, but anyone familiar with Haskell know of an easy and intuitive way to do something like:

allLists :: Integer -> Integer -> [[Integer]] allLists n len = ?
And allLists would return all lists of length len where each element is in the range 0..n?