From 485e005ea6e8d001bf15a1440a1609e775769e1f Mon Sep 17 00:00:00 2001 From: Danilo Reyes Date: Wed, 2 Apr 2025 22:03:13 -0600 Subject: [PATCH] sudoku solver now solves complex puzzles --- src/sudoku-hs/src/Main.hs | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/sudoku-hs/src/Main.hs b/src/sudoku-hs/src/Main.hs index 70574cc..9dc5c4f 100644 --- a/src/sudoku-hs/src/Main.hs +++ b/src/sudoku-hs/src/Main.hs @@ -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 - Just (r, c, opts) -> - listToMaybe - [ result - | n <- opts - , let g' = updateGrid g r c (Just n) - , Just result <- [solve 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'] + , 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 "