sudoku solver now solves complex puzzles

This commit is contained in:
Danilo Reyes 2025-04-02 22:03:13 -06:00
parent 8f2ae33e75
commit 485e005ea6

View File

@ -33,14 +33,20 @@ printGrid = putStrLn . unlines . map (unwords . map showCell)
where showCell = maybe "." show
solve :: Grid -> Maybe Grid
solve g = case nextCell g of
Nothing -> Just g
solve g
| isComplete g = Just g
| otherwise = case nextCell g of
Nothing -> Nothing
Just (r, c, opts) ->
listToMaybe
[ result
| n <- opts
, let g' = updateGrid g r c (Just n)
, Just result <- [solve g'] ]
, Just result <- [solve g']
, isComplete result ]
isComplete :: Grid -> Bool
isComplete = all (notElem Nothing)
nextCell :: Grid -> Maybe (Int, Int, [Int])
nextCell g =
@ -62,7 +68,7 @@ getRow :: Int -> Grid -> [Cell]
getRow r g = g !! r
getCol :: Int -> Grid -> [Cell]
getCol c g = map (!! c) g
getCol c = map (!! c)
getBox :: Int -> Int -> Grid -> [Cell]
getBox r c g =
@ -85,6 +91,6 @@ main = do
[filePath] -> do
grid <- readCSV filePath
case solve grid of
Nothing -> putStrLn "No solution found."
Nothing -> putStrLn "No complete solution found."
Just g -> printGrid g
_ -> putStrLn "Usage: sudoku-solver <sudoku.csv>"