"be consistent" PerlMonks

### Re: How to determine & record all possible variations for 5 items? (Haskell)

by kelan (Deacon)
 on May 19, 2005 at 14:59 UTC ( #458644=note: print w/replies, xml ) Need Help??

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?

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://458644]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2022-08-16 13:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?