Adds parallelism

Abhinav Sarkar 2018-07-18 16:45:20 +05:30
parent bf80a77cd8
commit f7613fb78b
2 changed files with 23 additions and 7 deletions

View File

@ -15,6 +15,8 @@ dependencies:
- base >= 4.7 && < 5 - base >= 4.7 && < 5
- containers - containers
- vector - vector
- parallel
- deepseq
executables: executables:
sudoku: sudoku:
@ -22,6 +24,9 @@ executables:
source-dirs: src source-dirs: src
ghc-options: ghc-options:
- -O2 - -O2
- -threaded
- -rtsopts
- -with-rtsopts=-N
dependencies: dependencies:
- split - split

View File

@ -13,6 +13,9 @@ import qualified Data.Foldable
import qualified Data.Vector import qualified Data.Vector
import Data.Vector ((!)) import Data.Vector ((!))
import qualified Data.Vector.Mutable import qualified Data.Vector.Mutable
import qualified Data.Maybe
import qualified Control.DeepSeq
import Control.Parallel.Strategies (withStrategy, rdeepseq, parBuffer)
fixM :: (Eq t, Monad m) => (t -> m t) -> t -> m t fixM :: (Eq t, Monad m) => (t -> m t) -> t -> m t
fixM f x = f x >>= \x' -> if x' == x then return x else fixM f x' fixM f x = f x >>= \x' -> if x' == x then return x else fixM f x'
@ -24,6 +27,10 @@ data Cell = Fixed {-# UNPACK #-} !Data.Word.Word16
| Possible {-# UNPACK #-} !Data.Word.Word16 | Possible {-# UNPACK #-} !Data.Word.Word16
deriving (Show, Eq) deriving (Show, Eq)
instance Control.DeepSeq.NFData Cell where
rnf (Fixed w) = Control.DeepSeq.rnf w
rnf (Possible w) = Control.DeepSeq.rnf w
type Grid = Data.Vector.Vector Cell type Grid = Data.Vector.Vector Cell
type CellIxs = [Int] type CellIxs = [Int]
@ -210,10 +217,14 @@ solve grid = pruneGrid grid >>= solve'
main :: IO () main :: IO ()
main = do main = do
inputs <- lines <$> getContents grids <- lines <$> getContents
Control.Monad.forM_ inputs $ \input -> let solutions = parMap readAndSolve grids
case readGrid input of putStrLn $
Nothing -> putStrLn "Invalid input" show (length $ filter Data.Maybe.isJust solutions) ++ "/" ++ show (length grids) ++ " solved"
Just grid -> case solve grid of where
Nothing -> putStrLn "No solution found" readAndSolve grid = case readGrid grid of
Just grid' -> putStrLn $ showGrid grid' Nothing -> Nothing
Just b -> solve b
chunkSize = 1000
parMap f = withStrategy (parBuffer chunkSize rdeepseq) . map f