From 0f6c8f99bf707073025b65ae985e7912c8c731bc Mon Sep 17 00:00:00 2001 From: Abhinav Sarkar Date: Thu, 21 Jun 2018 10:53:05 +0530 Subject: [PATCH] Uses traverse instead of sequence . map --- src/Sudoku.hs | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/Sudoku.hs b/src/Sudoku.hs index 417056a..9bd4620 100644 --- a/src/Sudoku.hs +++ b/src/Sudoku.hs @@ -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)