Jump to content

Ordered partitions: Difference between revisions

m
→‎{{header|Haskell}}: Tidied (applied Ormolu and Hlint to last example)
m (→‎{{header|Haskell}}: Tidied (applied Ormolu and Hlint to last example))
Line 1,193:
 
Faster by keeping track of the length of lists:
<lang haskell>--import chooseData.Bifunctor m out of n items(first, return tuple of chosen and the restsecond)
choose aa _ 0 = [([], aa)]
choose aa@(a:as) n m
| n == m = [(aa, [])]
| otherwise = map (\(x,y) -> (a:x, y)) (choose as (n-1) (m-1)) ++
map (\(x,y) -> (x, a:y)) (choose as (n-1) m)
 
-- choose m out of n items, return tuple of chosen and the rest
partitions x = combos [1..n] n x where
 
n = sum x
choose :: [Int] -> Int -> Int -> [([Int], [Int])]
combos _ _ [] = [[]]
choose aa[] _ 0_ = [([], aa[])]
combos s n (x:xs) = [ l : r | (l,rest) <- choose s n x,
rchoose <-aa combos_ rest0 = [(n[], - xaa) xs]
choose aa@(a : as) n m
| n == m = [(aa, [])]
| otherwise =
| otherwise = map (\(x,y) ->first (a:x, y):) (<$> choose as (n - 1) (m - 1)) ++
map (\(x,y) - <> (x,second (a :y)) (<$> choose as (n - 1) m)
 
partitions :: [Int] -> [[[Int]]]
partitions x = combos [1 .. n] n x where
where
n = sum x
combos _ _ [] = [[]]
combos s n (x : xs) =
[ l : r
combos s n (x:xs) = [ l : r| | (l, rest) <- choose s n x,
r <- combos rest (n - x) xs
]
 
main :: IO ()
main = mapM_ print $ partitions [5, 5, 5]</lang>
 
=={{header|J}}==
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.