Combinations with repetitions: Difference between revisions

m
→‎Dynamic Programming: Tidied manual recursion version
m (→‎Dynamic Programming: Tidied manual recursion version)
Line 1,536:
 
and another approach, using manual recursion:
<lang haskell>--------------- COMBINATIONS WITH REPETITION -------------
<lang haskell>combsWithRep
 
:: (Eq a)
combinationsWithRepetition ::
=> Int -> [a] -> [[a]]
:: (Eq a) =>
combsWithRep k xs = comb k []
Int ->
[a] ->
[[a]]
combinationsWithRepetition k xs = cmb k []
where
combcmb 0 ys = ys
combcmb n [] = combcmb (pred n) (pure <$> xs)
combcmb n peers = combcmb (pred n) (peers >>= nextLayer)
where
nextLayer ys@(h:_)[] = (: ys) <$> dropWhile (/= h) xs[]
nextLayer ys@(h : _) =
(: ys) <$> dropWhile (/= h) xs
 
 
-------------------------- TESTS -------------------------
main :: IO ()
main = do
print $
print $ combsWithRep 2 ["iced", "jam", "plain"]
combinationsWithRepetition
print $ length $ combsWithRep 3 [0 .. 9]</lang>
2
print $ combsWithRep 2 ["iced", "jam", "plain"]
print $ length $ combsWithRepcombinationsWithRepetition 3 [0 .. 9]</lang>
{{Out}}
<pre>[["iced","iced"],["jam","iced"],["plain","iced"],["jam","jam"],["plain","jam"],["plain","plain"]]
9,655

edits