| 1 |
{-# LANGUAGE DeriveFunctor #-} |
| 2 |
{-# LANGUAGE FlexibleInstances #-} |
| 3 |
{-# LANGUAGE MultiParamTypeClasses #-} |
| 4 |
|
| 5 |
-- | Efficient combinatorial algorithms over multisets, including |
| 6 |
-- generating all permutations, partitions, subsets, cycles, and |
| 7 |
-- other combinatorial structures based on multisets. Note that an |
| 8 |
-- 'Eq' or 'Ord' instance on the elements is /not/ required; the |
| 9 |
-- algorithms are careful to keep track of which things are (by |
| 10 |
-- construction) equal to which other things, so equality testing is |
| 11 |
-- not needed. |
| 12 |
module Math.Combinatorics.Multiset |
| 13 |
( -- * The 'Multiset' type |
| 14 |
|
| 15 |
Count |
| 16 |
, Multiset(..) |
| 17 |
, emptyMS, singletonMS |
| 18 |
, consMS, (+:) |
| 19 |
|
| 20 |
-- ** Conversions |
| 21 |
, toList |
| 22 |
, fromList |
| 23 |
, fromListEq |
| 24 |
, fromDistinctList |
| 25 |
, fromCounts |
| 26 |
, getCounts |
| 27 |
, size |
| 28 |
|
| 29 |
-- ** Operations |
| 30 |
, disjUnion |
| 31 |
, disjUnions |
| 32 |
|
| 33 |
-- * Permutations |
| 34 |
|
| 35 |
, permutations |
| 36 |
, permutationsRLE |
| 37 |
|
| 38 |
-- * Partitions |
| 39 |
|
| 40 |
, Vec |
| 41 |
, vPartitions |
| 42 |
, partitions |
| 43 |
|
| 44 |
-- * Submultisets |
| 45 |
|
| 46 |
, splits |
| 47 |
, kSubsets |
| 48 |
|
| 49 |
-- * Cycles and bracelets |
| 50 |
|
| 51 |
, cycles |
| 52 |
, bracelets |
| 53 |
, genFixedBracelets |
| 54 |
|
| 55 |
-- * Miscellaneous |
| 56 |
|
| 57 |
, sequenceMS |
| 58 |
|
| 59 |
) where |
| 60 |
|
| 61 |
import Control.Arrow (first, second, (&&&), (***)) |
| 62 |
import Control.Monad (forM_, when) |
| 63 |
import Control.Monad.Trans.Writer |
| 64 |
import qualified Data.IntMap.Strict as IM |
| 65 |
import Data.List (group, partition, sort) |
| 66 |
import Data.Maybe (catMaybes, fromJust) |
| 67 |
|
| 68 |
type Count = Int |
| 69 |
|
| 70 |
-- | A multiset is represented as a list of (element, count) pairs. |
| 71 |
-- We maintain the invariants that the counts are always positive, |
| 72 |
-- and no element ever appears more than once. |
| 73 |
newtype Multiset a = MS { toCounts :: [(a, Count)] } |
| 74 |
deriving (Show, Functor) |
| 75 |
|
| 76 |
-- | Construct a 'Multiset' from a list of (element, count) pairs. |
| 77 |
-- Precondition: the counts must all be positive, and there must not |
| 78 |
-- be any duplicate elements. |
| 79 |
fromCounts :: [(a, Count)] -> Multiset a |
| 80 |
fromCounts = MS |
| 81 |
|
| 82 |
-- | Extract just the element counts from a multiset, forgetting the |
| 83 |
-- elements. |
| 84 |
getCounts :: Multiset a -> [Count] |
| 85 |
getCounts = map snd . toCounts |
| 86 |
|
| 87 |
-- | Compute the total size of a multiset. |
| 88 |
size :: Multiset a -> Int |
| 89 |
size = sum . getCounts |
| 90 |
|
| 91 |
liftMS :: ([(a, Count)] -> [(b, Count)]) -> Multiset a -> Multiset b |
| 92 |
liftMS f (MS m) = MS (f m) |
| 93 |
|
| 94 |
-- | A multiset with no values in it. |
| 95 |
emptyMS :: Multiset a |
| 96 |
emptyMS = MS [] |
| 97 |
|
| 98 |
-- | Create a multiset with only a single value in it. |
| 99 |
singletonMS :: a -> Multiset a |
| 100 |
singletonMS a = MS [(a,1)] |
| 101 |
|
| 102 |
-- | Add an element with multiplicity to a multiset. Precondition: |
| 103 |
-- the new element is distinct from all elements already in the |
| 104 |
-- multiset. |
| 105 |
consMS :: (a, Count) -> Multiset a -> Multiset a |
| 106 |
consMS e@(_,c) (MS m) |
| 107 |
| c > 0 = MS (e:m) |
| 108 |
| otherwise = MS m |
| 109 |
|
| 110 |
-- | A convenient shorthand for 'consMS'. |
| 111 |
(+:) :: (a, Count) -> Multiset a -> Multiset a |
| 112 |
(+:) = consMS |
| 113 |
|
| 114 |
-- | Convert a multiset to a list. |
| 115 |
toList :: Multiset a -> [a] |
| 116 |
toList = expandCounts . toCounts |
| 117 |
|
| 118 |
expandCounts :: [(a, Count)] -> [a] |
| 119 |
expandCounts = concatMap (uncurry (flip replicate)) |
| 120 |
|
| 121 |
-- | Efficiently convert a list to a multiset, given an 'Ord' instance |
| 122 |
-- for the elements. This method is provided just for convenience. |
| 123 |
-- you can also use 'fromListEq' with only an 'Eq' instance, or |
| 124 |
-- construct 'Multiset's directly using 'fromCounts'. |
| 125 |
fromList :: Ord a => [a] -> Multiset a |
| 126 |
fromList = fromCounts . map (head &&& length) . group . sort |
| 127 |
|
| 128 |
-- | Convert a list to a multiset, given an 'Eq' instance for the |
| 129 |
-- elements. |
| 130 |
fromListEq :: Eq a => [a] -> Multiset a |
| 131 |
fromListEq = fromCounts . fromListEq' |
| 132 |
where fromListEq' [] = [] |
| 133 |
fromListEq' (x:xs) = (x, 1 + length xEqs) : fromListEq' xNeqs |
| 134 |
where |
| 135 |
(xEqs, xNeqs) = partition (==x) xs |
| 136 |
|
| 137 |
-- | Make a multiset with one copy of each element from a list of |
| 138 |
-- distinct elements. |
| 139 |
fromDistinctList :: [a] -> Multiset a |
| 140 |
fromDistinctList = fromCounts . map (\x -> (x,1)) |
| 141 |
|
| 142 |
-- | Form the disjoint union of two multisets; i.e. we assume the two |
| 143 |
-- multisets share no elements in common. |
| 144 |
disjUnion :: Multiset a -> Multiset a -> Multiset a |
| 145 |
disjUnion (MS xs) (MS ys) = MS (xs ++ ys) |
| 146 |
|
| 147 |
-- | Form the disjoint union of a collection of multisets. We assume |
| 148 |
-- that the multisets all have distinct elements. |
| 149 |
disjUnions :: [Multiset a] -> Multiset a |
| 150 |
disjUnions = foldr disjUnion (MS []) |
| 151 |
|
| 152 |
-- | In order to generate permutations of a multiset, we need to keep |
| 153 |
-- track of the most recently used element in the permutation being |
| 154 |
-- built, so that we don't use it again immediately. The |
| 155 |
-- 'RMultiset' type (for \"restricted multiset\") records this |
| 156 |
-- information, consisting of a multiset possibly paired with an |
| 157 |
-- element (with multiplicity) which is also part of the multiset, |
| 158 |
-- but should not be used at the beginning of permutations. |
| 159 |
data RMultiset a = RMS (Maybe (a, Count)) [(a,Count)] |
| 160 |
deriving Show |
| 161 |
|
| 162 |
-- | Convert a 'Multiset' to a 'RMultiset' (with no avoided element). |
| 163 |
toRMS :: Multiset a -> RMultiset a |
| 164 |
toRMS = RMS Nothing . toCounts |
| 165 |
|
| 166 |
-- | Convert a 'RMultiset' to a 'Multiset'. |
| 167 |
fromRMS :: RMultiset a -> Multiset a |
| 168 |
fromRMS (RMS Nothing m) = MS m |
| 169 |
fromRMS (RMS (Just e) m) = MS (e:m) |
| 170 |
|
| 171 |
-- | List all the distinct permutations of the elements of a |
| 172 |
-- multiset. |
| 173 |
-- |
| 174 |
-- For example, @permutations (fromList \"abb\") == |
| 175 |
-- [\"abb\",\"bba\",\"bab\"]@, whereas @Data.List.permutations |
| 176 |
-- \"abb\" == [\"abb\",\"bab\",\"bba\",\"bba\",\"bab\",\"abb\"]@. |
| 177 |
-- This function is equivalent to, but /much/ more efficient than, |
| 178 |
-- @nub . Data.List.permutations@, and even works when the elements |
| 179 |
-- have no 'Eq' instance. |
| 180 |
-- |
| 181 |
-- Note that this is a specialized version of 'permutationsRLE', |
| 182 |
-- where each run has been expanded via 'replicate'. |
| 183 |
permutations :: Multiset a -> [[a]] |
| 184 |
permutations = map expandCounts . permutationsRLE |
| 185 |
|
| 186 |
-- | List all the distinct permutations of the elements of a multiset, |
| 187 |
-- with each permutation run-length encoded. (Note that the |
| 188 |
-- run-length encoding is a natural byproduct of the algorithm used, |
| 189 |
-- not a separate postprocessing step.) |
| 190 |
-- |
| 191 |
-- For example, @permutationsRLE [('a',1), ('b',2)] == |
| 192 |
-- [[('a',1),('b',2)],[('b',2),('a',1)],[('b',1),('a',1),('b',1)]]@. |
| 193 |
-- |
| 194 |
-- (Note that although the output type is newtype-equivalent to |
| 195 |
-- @[Multiset a]@, we don't call it that since the output may |
| 196 |
-- violate the 'Multiset' invariant that no element should appear |
| 197 |
-- more than once. And indeed, morally this function does not |
| 198 |
-- output multisets at all.) |
| 199 |
permutationsRLE :: Multiset a -> [[(a,Count)]] |
| 200 |
permutationsRLE (MS []) = [[]] |
| 201 |
permutationsRLE m = permutationsRLE' (toRMS m) |
| 202 |
|
| 203 |
-- | List all the (run-length encoded) distinct permutations of the |
| 204 |
-- elements of a multiset which do not start with the element to |
| 205 |
-- avoid (if any). |
| 206 |
permutationsRLE' :: RMultiset a -> [[(a,Count)]] |
| 207 |
|
| 208 |
-- If only one element is left, there's only one permutation. |
| 209 |
permutationsRLE' (RMS Nothing [(x,n)]) = [[(x,n)]] |
| 210 |
|
| 211 |
-- Otherwise, select an element+multiplicity in all possible ways, and |
| 212 |
-- concatenate the elements to all possible permutations of the |
| 213 |
-- remaining multiset. |
| 214 |
permutationsRLE' m = [ e : p |
| 215 |
| (e, m') <- selectRMS m |
| 216 |
, p <- permutationsRLE' m' |
| 217 |
] |
| 218 |
|
| 219 |
-- | Select an element + multiplicity from a multiset in all possible |
| 220 |
-- ways, appropriately keeping track of elements to avoid at the |
| 221 |
-- start of permutations. |
| 222 |
selectRMS :: RMultiset a -> [((a, Count), RMultiset a)] |
| 223 |
|
| 224 |
-- No elements to select. |
| 225 |
selectRMS (RMS _ []) = [] |
| 226 |
|
| 227 |
-- Selecting from a multiset with n copies of x, avoiding e: |
| 228 |
selectRMS (RMS e ((x,n) : ms)) = |
| 229 |
|
| 230 |
-- If we select all n copies of x, there are no copies of x left to avoid; |
| 231 |
-- stick e (if it exists) back into the remaining multiset. |
| 232 |
((x,n), RMS Nothing (maybe ms (:ms) e)) : |
| 233 |
|
| 234 |
-- We can also select any number of copies of x from (n-1) down to 1; in each case, |
| 235 |
-- we avoid the remaining copies of x and put e back into the returned multiset. |
| 236 |
[ ( (x,k), RMS (Just (x,n-k)) |
| 237 |
(maybe ms (:ms) e) ) |
| 238 |
| k <- [n-1, n-2 .. 1] |
| 239 |
] ++ |
| 240 |
|
| 241 |
-- Finally, we can recursively choose something other than x. |
| 242 |
map (second (consRMS (x,n))) (selectRMS (RMS e ms)) |
| 243 |
|
| 244 |
consRMS :: (a, Count) -> RMultiset a -> RMultiset a |
| 245 |
consRMS x (RMS e m) = RMS e (x:m) |
| 246 |
|
| 247 |
|
| 248 |
-- Some QuickCheck properties. Of course, due to combinatorial |
| 249 |
-- explosion these are of limited utility! |
| 250 |
-- newtype ArbCount = ArbCount Int |
| 251 |
-- deriving (Eq, Show, Num, Real, Enum, Ord, Integral) |
| 252 |
|
| 253 |
-- instance Arbitrary Count where |
| 254 |
-- arbitrary = elements (map ArbCount [1..3]) |
| 255 |
|
| 256 |
-- prop_perms_distinct :: Multiset Char ArbCount -> Bool |
| 257 |
-- prop_perms_distinct m = length ps == length (nub ps) |
| 258 |
-- where ps = permutations m |
| 259 |
|
| 260 |
-- prop_perms_are_perms :: Multiset Char ArbCount -> Bool |
| 261 |
-- prop_perms_are_perms m = all ((==l') . sort) (permutations m) |
| 262 |
-- where l' = sort (toList m) |
| 263 |
|
| 264 |
--------------------- |
| 265 |
-- Partitions |
| 266 |
--------------------- |
| 267 |
|
| 268 |
-- | Element count vector. |
| 269 |
type Vec = [Count] |
| 270 |
|
| 271 |
-- | Componentwise comparison of count vectors. |
| 272 |
(<|=) :: Vec -> Vec -> Bool |
| 273 |
xs <|= ys = and $ zipWith (<=) xs ys |
| 274 |
|
| 275 |
-- | 'vZero v' produces a zero vector of the same length as @v@. |
| 276 |
vZero :: Vec -> Vec |
| 277 |
vZero = map (const 0) |
| 278 |
|
| 279 |
-- | Test for the zero vector. |
| 280 |
vIsZero :: Vec -> Bool |
| 281 |
vIsZero = all (==0) |
| 282 |
|
| 283 |
-- | Do vector arithmetic componentwise. |
| 284 |
(.+.), (.-.) :: Vec -> Vec -> Vec |
| 285 |
(.+.) = zipWith (+) |
| 286 |
(.-.) = zipWith (-) |
| 287 |
|
| 288 |
-- | Multiply a count vector by a scalar. |
| 289 |
(*.) :: Count -> Vec -> Vec |
| 290 |
(*.) n = map (n*) |
| 291 |
|
| 292 |
-- | 'v1 `vDiv` v2' is the largest scalar multiple of 'v2' which is |
| 293 |
-- elementwise less than or equal to 'v1'. |
| 294 |
vDiv :: Vec -> Vec -> Count |
| 295 |
vDiv v1 v2 = minimum . catMaybes $ zipWith zdiv v1 v2 |
| 296 |
where zdiv _ 0 = Nothing |
| 297 |
zdiv x y = Just $ x `div` y |
| 298 |
|
| 299 |
-- | 'vInc within v' lexicographically increments 'v' with respect to |
| 300 |
-- 'within'. For example, @vInc [2,3,5] [1,3,4] == [1,3,5]@, and |
| 301 |
-- @vInc [2,3,5] [1,3,5] == [2,0,0]@. |
| 302 |
vInc :: Vec -> Vec -> Vec |
| 303 |
vInc lim v = reverse (vInc' (reverse lim) (reverse v)) |
| 304 |
where vInc' _ [] = [] |
| 305 |
vInc' [] (x:xs) = x+1 : xs |
| 306 |
vInc' (l:ls) (x:xs) | x < l = x+1 : xs |
| 307 |
| otherwise = 0 : vInc' ls xs |
| 308 |
|
| 309 |
-- | Generate all vector partitions, representing each partition as a |
| 310 |
-- multiset of vectors. |
| 311 |
-- |
| 312 |
-- This code is a slight generalization of the code published in |
| 313 |
-- |
| 314 |
-- Brent Yorgey. \"Generating Multiset Partitions\". In: The |
| 315 |
-- Monad.Reader, Issue 8, September 2007. |
| 316 |
-- <http://www.haskell.org/sitewiki/images/d/dd/TMR-Issue8.pdf> |
| 317 |
-- |
| 318 |
-- See that article for a detailed discussion of the code and how it works. |
| 319 |
vPartitions :: Vec -> [Multiset Vec] |
| 320 |
vPartitions v = vPart v (vZero v) where |
| 321 |
vPart v _ | vIsZero v = [MS []] |
| 322 |
vPart v vL |
| 323 |
| v <= vL = [] |
| 324 |
| otherwise = MS [(v,1)] |
| 325 |
: [ (v',k) +: p' | v' <- withinFromTo v (vHalf v) (vInc v vL) |
| 326 |
, k <- [1 .. (v `vDiv` v')] |
| 327 |
, p' <- vPart (v .-. (k *. v')) v' ] |
| 328 |
|
| 329 |
-- | 'vHalf v' computes the \"lexicographic half\" of 'v', that is, |
| 330 |
-- the vector which is the middle element (biased towards the end) |
| 331 |
-- in a lexicographically decreasing list of all the vectors |
| 332 |
-- elementwise no greater than 'v'. |
| 333 |
vHalf :: Vec -> Vec |
| 334 |
vHalf [] = [] |
| 335 |
vHalf (x:xs) | (even x) = (x `div` 2) : vHalf xs |
| 336 |
| otherwise = (x `div` 2) : xs |
| 337 |
|
| 338 |
downFrom n = [n,(n-1)..0] |
| 339 |
|
| 340 |
-- | 'within m' generates a lexicographically decreasing list of |
| 341 |
-- vectors elementwise no greater than 'm'. |
| 342 |
within :: Vec -> [Vec] |
| 343 |
within = sequence . map downFrom |
| 344 |
|
| 345 |
-- | Clip one vector against another. |
| 346 |
clip :: Vec -> Vec -> Vec |
| 347 |
clip = zipWith min |
| 348 |
|
| 349 |
-- | 'withinFromTo m s e' efficiently generates a lexicographically |
| 350 |
-- decreasing list of vectors which are elementwise no greater than |
| 351 |
-- 'm' and lexicographically between 's' and 'e'. |
| 352 |
withinFromTo :: Vec -> Vec -> Vec -> [Vec] |
| 353 |
withinFromTo m s e | not (s <|= m) = withinFromTo m (clip m s) e |
| 354 |
withinFromTo m s e | e > s = [] |
| 355 |
withinFromTo m s e = wFT m s e True True |
| 356 |
where |
| 357 |
wFT [] _ _ _ _ = [[]] |
| 358 |
wFT (m:ms) (s:ss) (e:es) useS useE = |
| 359 |
let start = if useS then s else m |
| 360 |
end = if useE then e else 0 |
| 361 |
in |
| 362 |
[x:xs | x <- [start,(start-1)..end], |
| 363 |
let useS' = useS && x==s, |
| 364 |
let useE' = useE && x==e, |
| 365 |
xs <- wFT ms ss es useS' useE' ] |
| 366 |
|
| 367 |
-- | Efficiently generate all distinct multiset partitions. Note that |
| 368 |
-- each partition is represented as a multiset of parts (each of |
| 369 |
-- which is a multiset) in order to properly reflect the fact that |
| 370 |
-- some parts may occur multiple times. |
| 371 |
partitions :: Multiset a -> [Multiset (Multiset a)] |
| 372 |
partitions (MS []) = [MS []] |
| 373 |
partitions (MS m) = (map . fmap) (combine elts) $ vPartitions counts |
| 374 |
where (elts, counts) = unzip m |
| 375 |
combine es cs = MS . filter ((/=0) . snd) $ zip es cs |
| 376 |
|
| 377 |
-- | Generate all splittings of a multiset into two submultisets, |
| 378 |
-- i.e. all size-two partitions. |
| 379 |
splits :: Multiset a -> [(Multiset a, Multiset a)] |
| 380 |
splits (MS []) = [(MS [], MS [])] |
| 381 |
splits (MS ((x,n):m)) = |
| 382 |
for [0..n] $ \k -> |
| 383 |
map (addElt x k *** addElt x (n-k)) (splits (MS m)) |
| 384 |
|
| 385 |
-- | Generate all size-k submultisets. |
| 386 |
kSubsets :: Count -> Multiset a -> [Multiset a] |
| 387 |
kSubsets 0 _ = [MS []] |
| 388 |
kSubsets _ (MS []) = [] |
| 389 |
kSubsets k (MS ((x,n):m)) = |
| 390 |
for [0 .. min k n] $ \j -> |
| 391 |
map (addElt x j) (kSubsets (k - j) (MS m)) |
| 392 |
|
| 393 |
for = flip concatMap |
| 394 |
|
| 395 |
addElt _ 0 = id |
| 396 |
addElt x k = ((x,k) +:) |
| 397 |
|
| 398 |
---------------------------------------------------------------------- |
| 399 |
-- Cycles (aka Necklaces) |
| 400 |
---------------------------------------------------------------------- |
| 401 |
|
| 402 |
-- | Generate all distinct cycles, aka necklaces, with elements taken |
| 403 |
-- from a multiset. See J. Sawada, \"A fast algorithm to generate |
| 404 |
-- necklaces with fixed content\", J. Theor. Comput. Sci. 301 (2003) |
| 405 |
-- pp. 477-489. |
| 406 |
-- |
| 407 |
-- Given the ordering on the elements of the multiset based on their |
| 408 |
-- position in the multiset representation (with \"smaller\" |
| 409 |
-- elements first), in @map reverse (cycles m)@, each generated |
| 410 |
-- cycle is lexicographically smallest among all its cyclic shifts, |
| 411 |
-- and furthermore, the cycles occur in reverse lexicographic |
| 412 |
-- order. (It's simply more convenient/efficient to generate the |
| 413 |
-- cycles reversed in this way, and of course we get the same set of |
| 414 |
-- cycles either way.) |
| 415 |
-- |
| 416 |
-- For example, @cycles (fromList \"aabbc\") == |
| 417 |
-- [\"cabba\",\"bcaba\",\"cbaba\",\"bbcaa\",\"bcbaa\",\"cbbaa\"]@. |
| 418 |
cycles :: Multiset a -> [[a]] |
| 419 |
cycles (MS []) = [] -- no such thing as an empty cycle |
| 420 |
cycles m@(MS ((x1,n1):xs)) |
| 421 |
| n1 == 1 = (cycles' n 2 1 [(0,x1)] (reverse $ zip [1..] xs)) |
| 422 |
| otherwise = (cycles' n 2 1 [(0,x1)] (reverse $ zip [0..] ((x1,n1-1):xs))) |
| 423 |
where n = sum . getCounts $ m |
| 424 |
|
| 425 |
-- | The first parameter is the length of the necklaces being |
| 426 |
-- generated. The second parameter @p@ is the length of the longest |
| 427 |
-- prefix of @pre@ which is a Lyndon word, i.e. an aperiodic |
| 428 |
-- necklace. @pre@ is the current (reversed) prefix of the |
| 429 |
-- necklaces being generated. |
| 430 |
cycles' :: Int -> Int -> Int -> [(Int, a)] -> [(Int, (a,Count))] -> [[a]] |
| 431 |
cycles' n _ p pre [] | n `mod` p == 0 = [map snd pre] |
| 432 |
| otherwise = [] |
| 433 |
|
| 434 |
cycles' n t p pre xs = |
| 435 |
(takeWhile ((>=atp) . fst) xs) >>= \(j, (xj,_)) -> |
| 436 |
cycles' n (t+1) (if j == atp then p else t) |
| 437 |
((j,xj):pre) |
| 438 |
(remove j xs) |
| 439 |
where atp = fst $ pre !! (p - 1) |
| 440 |
|
| 441 |
remove :: Int -> [(Int, (a, Int))] -> [(Int, (a, Int))] |
| 442 |
remove _ [] = [] |
| 443 |
remove j (x@(j',(xj,nj)):xs) |
| 444 |
| j == j' && nj == 1 = xs |
| 445 |
| j == j' = (j',(xj,nj-1)):xs |
| 446 |
| otherwise = x:remove j xs |
| 447 |
|
| 448 |
---------------------------------------------------------------------- |
| 449 |
-- Bracelets |
| 450 |
---------------------------------------------------------------------- |
| 451 |
|
| 452 |
-- Some utilities |
| 453 |
|
| 454 |
-------------------------------------------------- |
| 455 |
-- Indexable and Snocable classes |
| 456 |
|
| 457 |
class Snocable p a where |
| 458 |
(|>) :: p -> a -> p |
| 459 |
|
| 460 |
-- 1-based indexing |
| 461 |
class Indexable p where |
| 462 |
(!) :: p -> Int -> Int |
| 463 |
|
| 464 |
-------------------------------------------------- |
| 465 |
-- Prenecklaces |
| 466 |
|
| 467 |
type PreNecklace = [Int] |
| 468 |
|
| 469 |
-- A prenecklace, stored backwards, along with its length and its |
| 470 |
-- first element cached for quick retrieval. |
| 471 |
data Pre = Pre !Int (Maybe Int) PreNecklace |
| 472 |
deriving (Show) |
| 473 |
|
| 474 |
emptyPre :: Pre |
| 475 |
emptyPre = Pre 0 Nothing [] |
| 476 |
|
| 477 |
getPre :: Pre -> PreNecklace |
| 478 |
getPre (Pre _ _ as) = reverse as |
| 479 |
|
| 480 |
instance Snocable Pre Int where |
| 481 |
(Pre 0 _ []) |> a = Pre 1 (Just a) [a] |
| 482 |
(Pre t a1 as) |> a = Pre (t+1) a1 (a:as) |
| 483 |
|
| 484 |
instance Indexable Pre where |
| 485 |
_ ! 0 = 0 |
| 486 |
(Pre _ (Just a1) _) ! 1 = a1 |
| 487 |
(Pre t _ as) ! i = as !! (t-i) |
| 488 |
-- as stores a_t .. a_1. |
| 489 |
-- a_1 is the last element, i.e. with index t-1. |
| 490 |
-- a_2 has index t-2. |
| 491 |
-- In general, a_i has index t-i. |
| 492 |
|
| 493 |
-------------------------------------------------- |
| 494 |
-- Run-length encoding |
| 495 |
|
| 496 |
-- Run-length encodings. Stored in *reverse* order for easy access to |
| 497 |
-- the end. |
| 498 |
data RLE a = RLE !Int !Int [(a,Int)] |
| 499 |
deriving (Show) |
| 500 |
-- First Int is the total length of the decoded list. |
| 501 |
-- Second Int is the number of blocks. |
| 502 |
|
| 503 |
emptyRLE :: RLE a |
| 504 |
emptyRLE = RLE 0 0 [] |
| 505 |
|
| 506 |
compareRLE :: Ord a => [(a,Int)] -> [(a,Int)] -> Ordering |
| 507 |
compareRLE [] [] = EQ |
| 508 |
compareRLE [] _ = LT |
| 509 |
compareRLE _ [] = GT |
| 510 |
compareRLE ((a1,n1):rle1) ((a2,n2):rle2) |
| 511 |
| (a1,n1) == (a2,n2) = compareRLE rle1 rle2 |
| 512 |
| a1 < a2 = LT |
| 513 |
| a1 > a2 = GT |
| 514 |
| (n1 < n2 && (null rle1 || fst (head rle1) < a2)) || (n1 > n2 && not (null rle2) && a1 < fst (head rle2)) = LT |
| 515 |
| otherwise = GT |
| 516 |
|
| 517 |
instance Indexable (RLE Int) where |
| 518 |
(RLE _ _ []) ! _ = error "Bad index in (!) for RLE" |
| 519 |
(RLE n b ((a,v):rest)) ! i |
| 520 |
| i <= v = a |
| 521 |
| otherwise = (RLE (n-v) (b-1) rest) ! (i-v) |
| 522 |
|
| 523 |
instance Eq a => Snocable (RLE a) a where |
| 524 |
(RLE _ _ []) |> a' = RLE 1 1 [(a',1)] |
| 525 |
(RLE n b rle@((a,v):rest)) |> a' |
| 526 |
| a == a' = RLE (n+1) b ((a,v+1):rest) |
| 527 |
| otherwise = RLE (n+1) (b+1) ((a',1):rle) |
| 528 |
|
| 529 |
-------------------------------------------------- |
| 530 |
-- Prenecklaces + RLE |
| 531 |
|
| 532 |
-- Prenecklaces along with a run-length encoding. |
| 533 |
data Pre' = Pre' Pre (RLE Int) |
| 534 |
deriving Show |
| 535 |
|
| 536 |
emptyPre' :: Pre' |
| 537 |
emptyPre' = Pre' emptyPre emptyRLE |
| 538 |
|
| 539 |
getPre' :: Pre' -> PreNecklace |
| 540 |
getPre' (Pre' pre _) = getPre pre |
| 541 |
|
| 542 |
instance Indexable Pre' where |
| 543 |
_ ! 0 = 0 |
| 544 |
(Pre' (Pre len _ _) rle) ! i = rle ! (len - i + 1) |
| 545 |
|
| 546 |
instance Snocable Pre' Int where |
| 547 |
(Pre' p rle) |> a = Pre' (p |> a) (rle |> a) |
| 548 |
|
| 549 |
-------------------------------------------------- |
| 550 |
-- Bracelet generation |
| 551 |
|
| 552 |
type Bracelet = [Int] |
| 553 |
|
| 554 |
-- | An optimized bracelet generation algorithm, based on |
| 555 |
-- S. Karim et al, "Generating Bracelets with Fixed Content". |
| 556 |
-- <http://www.cis.uoguelph.ca/~sawada/papers/fix-brace.pdf> |
| 557 |
-- |
| 558 |
-- @genFixedBracelets n content@ produces all bracelets (unique up |
| 559 |
-- to rotation and reflection) of length @n@ using @content@, which |
| 560 |
-- consists of a list of pairs where the pair (a,i) indicates that |
| 561 |
-- element a may be used up to i times. It is assumed that the elements |
| 562 |
-- are drawn from [0..k]. |
| 563 |
genFixedBracelets :: Int -> [(Int,Int)] -> [Bracelet] |
| 564 |
genFixedBracelets n [(0,k)] | k >= n = [replicate k 0] |
| 565 |
| otherwise = [] |
| 566 |
genFixedBracelets n content = execWriter (go 1 1 0 (IM.fromList content) emptyPre') |
| 567 |
where |
| 568 |
go :: Int -> Int -> Int -> IM.IntMap Int -> Pre' -> Writer [Bracelet] () |
| 569 |
go _ _ _ con _ | IM.keys con == [0] = return () |
| 570 |
go t p r con pre@(Pre' (Pre _ _ as) _) |
| 571 |
| t > n = |
| 572 |
when (take (n - r) as >= reverse (take (n-r) as) && n `mod` p == 0) $ |
| 573 |
tell [getPre' pre] |
| 574 |
| otherwise = do |
| 575 |
let a' = pre ! (t-p) |
| 576 |
forM_ (dropWhile (< a') $ IM.keys con) $ \j -> do |
| 577 |
let con' = decrease j con |
| 578 |
pre' = pre |> j |
| 579 |
c = checkRev2 t pre' |
| 580 |
p' | j /= a' = t |
| 581 |
| otherwise = p |
| 582 |
when (c == EQ) $ go (t+1) p' t con' pre' |
| 583 |
when (c == GT) $ go (t+1) p' r con' pre' |
| 584 |
|
| 585 |
decrease :: Int -> IM.IntMap Int -> IM.IntMap Int |
| 586 |
decrease j con |
| 587 |
| IM.null con = con |
| 588 |
| otherwise = IM.alter q j con |
| 589 |
where |
| 590 |
q (Just 1) = Nothing |
| 591 |
q (Just cnt) = Just (cnt-1) |
| 592 |
q _ = Nothing |
| 593 |
|
| 594 |
checkRev2 _ (Pre' _ (RLE _ _ rle)) = compareRLE rle (reverse rle) |
| 595 |
|
| 596 |
-- | Generate all distinct bracelets (lists considered equivalent up |
| 597 |
-- to rotation and reversal) from a given multiset. The generated |
| 598 |
-- bracelets are in lexicographic order, and each is |
| 599 |
-- lexicographically smallest among its rotations and reversals. |
| 600 |
-- See @genFixedBracelets@ for a slightly more general routine with |
| 601 |
-- references. |
| 602 |
-- |
| 603 |
-- For example, @bracelets $ fromList \"RRRRRRRLLL\"@ yields |
| 604 |
-- |
| 605 |
-- > ["LLLRRRRRRR","LLRLRRRRRR","LLRRLRRRRR","LLRRRLRRRR" |
| 606 |
-- > ,"LRLRLRRRRR","LRLRRLRRRR","LRLRRRLRRR","LRRLRRLRRR"] |
| 607 |
bracelets :: Multiset a -> [[a]] |
| 608 |
bracelets ms@(MS cnts) = bs |
| 609 |
where |
| 610 |
contentMap = IM.fromList (zip [0..] (map fst cnts)) |
| 611 |
content = zipWith (\i (_,n) -> (i,n)) [0..] cnts |
| 612 |
rawBs = genFixedBracelets (size ms) content |
| 613 |
bs = map (map (fromJust . flip IM.lookup contentMap)) rawBs |
| 614 |
|
| 615 |
---------------------------------------------------------------------- |
| 616 |
-- sequenceMS |
| 617 |
---------------------------------------------------------------------- |
| 618 |
|
| 619 |
-- | Take a multiset of lists, and select one element from each list |
| 620 |
-- in every possible combination to form a list of multisets. We |
| 621 |
-- assume that all the list elements are distinct. |
| 622 |
sequenceMS :: Multiset [a] -> [Multiset a] |
| 623 |
sequenceMS = map disjUnions |
| 624 |
. sequence |
| 625 |
. map (\(xs, n) -> kSubsets n (MS $ uncollate (xs, n))) |
| 626 |
. toCounts |
| 627 |
|
| 628 |
uncollate :: ([a], Count) -> [(a, Count)] |
| 629 |
uncollate (xs, n) = map (\x -> (x,n)) xs |