Question

I have a code in haskell which generates three-part composition of number:

kompozycje n = [ (x,y,z) | x<-[1..n], y<-[1..n], z<-[1..n], x+y+z==n]

I would like to make something like kompozycje n k which would generate me k-part compositions and then if for example k would equal 4 there would be four variables and four numbers returned and in condition there would be something like u+x+y+z==n. Is there some simple solution for that?

Was it helpful?

Solution

Yes, yes there is. It uses the list monad and replicateM.

import Control.Monad

summy :: Integer -> Integer -> [[Integer]]
summy k n = do
  ls <- replicateM k [1..n]
  guard (sum ls == n)
  return ls

Or just

summy k n = filter ((==n) . sum) $ replicateM k [1..n]

In the list monad, replicateM will generate all possible lists of length k composed of the numbers 1 .. n.

This does generate duplicates, like [1, 2, 1] and [1, 1, 2]. But so does your original methods.

OTHER TIPS

As it happens, there's a lovely, efficient, and obscure (?) algorithm for enumerating the k-size partitions of n dating back to at least 1779. Donald Knuth -- who else? -- describes it in detail in a draft of the Art of Computer Programming, under Algorithm H. Here for your delectation is the algorithm in Haskell:

import Data.List (unfoldr)

partitions :: Int -> Int -> [[Int]]
partitions k n | k < 1 || k > n = []
partitions k n = initPartition : unfoldr (fmap (\x -> (x, x)) . nextPartition) initPartition
  where
    initPartition = (n-k+1) : replicate (k-1) 1

nextPartition :: [Int] -> Maybe [Int]
nextPartition [] = error "nextPartition should never be passed an empty list"
nextPartition [x] = Nothing
nextPartition (x:y:rest)
    | x-y > 1 = Just $ (x-1) : (y+1) : rest
    | otherwise = do
        (s, c, xs) <- go (x+y-1) rest
        Just $ (s-c) : c : xs
  where
    go _ [] = Nothing
    go s (z:zs)
        | x-z > 1 = let z' = z+1 in Just (s, z', z' : zs)
        | otherwise = do
            (s', c, zs') <- go (s+z) zs
            Just (s'-c, c, c:zs')

This is really a comment on @Aaron Roth's answer, which is good (and way more efficient than the accepted answer).

I think you can improve this, the fmap seems unnecessary. Also Knuth's presentation of H5/H6 (your 'go' step) obscures that it is just a sum & replicate. Here's a version that sticks close to Knuth's naming, while trying to make the algorithm clearer:

import Data.List (unfoldr)

partitions m n
  | n < m || n < 1 || m < 1 = []
  | otherwise = unfoldr nextPartition ((n - m + 1) : (replicate (m - 1) 1))

nextPartition [] = Nothing
nextPartition [a] = Just ([a], [])
nextPartition a@(a1 : a2 : rest)
  | a2 < a1 - 1 = Just (a, (a1 - 1):(a2 + 1):rest)
  | otherwise = Just (a, h5 (span (>= a1 - 1) rest))
  where
    h5 (_, []) = []
    h5 (xs, aj:ys) =
      let j = length xs + 3 in
      let tweaked = replicate (j - 1) (aj + 1) in
      let a1' = sum (take j a) - sum tweaked in
      a1' : tweaked ++ drop j a

Or recognizing that Knuth's H3 is just unrolling the loop once, we can write nextPartition compactly as:

nextPartition [] = Nothing
nextPartition a@(a1 : rest) =
  Just (a, -- H2
    case (span (>= a1 - 1) rest) of -- H4
      (_, []) -> [] -- H5, termination
      (xs, aj:ys) ->
        a1 + sum (xs) + aj - (length xs + 1) * (aj + 1) -- H6 "Finally..."
        : replicate (length xs + 1) (aj + 1) ++ ys) -- H5/H6 

Edited to add: Came back to this by accident a year later, and looking at the above, I don't know why I didn't just suggest this simpler recursive solution:

part m n = part2 (n-m+1) m n
  where
    part2 t m n
      | m == 1 && t == n = [[t]]
      | n < m || n < 1 || m < 1 || t < 1 = []
      | otherwise = [t:r|r <- part2 t (m-1) (n-t)] ++ (part2 (t-1) m n)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top