Uses traverse instead of sequence . map

custom-accumulator
Abhinav Sarkar 2018-06-21 10:53:05 +05:30
parent 97da7c92f9
commit 0f6c8f99bf
1 changed files with 17 additions and 17 deletions

View File

@ -13,8 +13,7 @@ type Grid = [Row]
readGrid :: String -> Maybe Grid
readGrid s
| length s == 81 =
sequence . map (sequence . map readCell) . Data.List.Split.chunksOf 9 $ s
| length s == 81 = traverse (traverse readCell) . Data.List.Split.chunksOf 9 $ s
| otherwise = Nothing
where
readCell '.' = Just $ Possible [1..9]
@ -38,36 +37,38 @@ showGridWithPossibilities = unlines . map (unwords . map showCell)
$ [1..9]
pruneCells :: [Cell] -> Maybe [Cell]
pruneCells cells = sequence . map pruneCell $ cells
pruneCells cells = traverse pruneCell cells
where
fixeds = [x | Fixed x <- cells]
pruneCell (Possible xs) = case xs Data.List.\\ fixeds of
[] -> Nothing
[y] -> Just $ Fixed y
ys -> Just $ Possible ys
pruneCell x = Just x
blocksToRows :: Grid -> Grid
blocksToRows =
concatMap (\rows -> let (r1:r2:r3:_) = map (Data.List.Split.chunksOf 3) rows
subGridsToRows :: Grid -> Grid
subGridsToRows =
concatMap (\rows -> let [r1, r2, r3] = map (Data.List.Split.chunksOf 3) rows
in zipWith3 (\a b c -> a ++ b ++ c) r1 r2 r3)
. Data.List.Split.chunksOf 3
pruneGrid' :: Grid -> Maybe Grid
pruneGrid' grid =
traverse pruneCells grid
>>= fmap Data.List.transpose . traverse pruneCells . Data.List.transpose
>>= fmap subGridsToRows . traverse pruneCells . subGridsToRows
pruneGrid :: Grid -> Maybe Grid
pruneGrid = fixM pruneGrid'
pruneGrid' grid =
sequence (map pruneCells grid)
>>= fmap Data.List.transpose . sequence . map pruneCells . Data.List.transpose
>>= fmap blocksToRows . sequence . map pruneCells . blocksToRows
fixM f x = f x >>= \x' -> if x' == x then return x else fixM f x'
where
fixM f x = f x >>= \x' -> if x' == x then return x else fixM f x'
isInvalidGrid :: Grid -> Bool
isInvalidGrid grid =
any isInvalidRow grid
|| any isInvalidRow (Data.List.transpose grid)
|| any isInvalidRow (blocksToRows grid)
|| any isInvalidRow (subGridsToRows grid)
where
isInvalidRow = not . isValidRow
isValidRow row =
@ -92,9 +93,8 @@ solve grid
possibleVals (Possible xs) = xs
smallestPossible =
head
. Data.List.sortBy (compare `Data.Function.on` (length . possibleVals . snd))
$ [(i, c) | (i, c@(Possible _)) <- zip [0..] $ concat grid]
Data.List.minimumBy (compare `Data.Function.on` (length . possibleVals . snd))
[(i, c) | (i, c@(Possible _)) <- zip [0..] $ concat grid]
splitPossible (i, Possible (x:[y])) = (i, Fixed x, Fixed y)
splitPossible (i, Possible (x:xs)) = (i, Fixed x, Possible xs)