我在haskell中有一个代码,它生成数字的三部分组合:
kompozycje n = [ (x,y,z) | x<-[1..n], y<-[1..n], z<-[1..n], x+y+z==n]
我想制作类似kompozycje nk的东西,它会生成我的k-part组合,然后如果例如k等于4则会有四个变量和四个数字返回,并且在条件下会有类似u + x +的东西Y + Z ==ñ。对此有一些简单的解决方案吗?
答案 0 :(得分:9)
是的,是的。它使用列表monad和replicateM
。
import Control.Monad
summy :: Integer -> Integer -> [[Integer]]
summy k n = do
ls <- replicateM k [1..n]
guard (sum ls == n)
return ls
或者只是
summy k n = filter ((==n) . sum) $ replicateM k [1..n]
在列表monad中,replicateM
将生成由数字k
组成的所有可能的长度为1 .. n
的列表。
这会生成重复项,例如[1, 2, 1]
和[1, 1, 2]
。但你的原始方法也是如此。
答案 1 :(得分:3)
碰巧的是,有一个可爱,高效且模糊(?)的算法,用于枚举k
大小的n
分区,其历史可以追溯到1779年.Donald Knuth - 还有谁? - 在Algorithm H下的计算机程序设计艺术草案中详细描述。在这里,你的选择是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')
答案 2 :(得分:1)
这真的是对@Aaron Roth的答案的评论,这很好(并且比接受的答案更有效率。)
我认为你可以改进这一点,fmap似乎没必要。此外,Knuth对H5 / H6的介绍(你的'走'步骤)模糊了它只是一个总和&amp;复制。这是一个贴近Knuth命名的版本,同时试图让算法更清晰:
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
或者认识到Knuth的H3只是将循环展开一次,我们可以将nextPartition紧凑地写为:
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
编辑补充:一年后意外地回到这一点,看看上面的内容,我不知道为什么我不只是建议这个更简单的递归解决方案:
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)