Created
June 16, 2014 23:15
-
-
Save anonymous/99bc650c41e07364764c to your computer and use it in GitHub Desktop.
A slow solution to the goat, wolf, lion problem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE BangPatterns #-} | |
-- tdp93422 over in yahoo.com land. | |
import qualified Data.Set as S | |
import Data.List (foldl') | |
import System.Environment (getArgs) | |
main :: IO () | |
main = do | |
args <- getArgs | |
putStrLn $ "goats: " ++ (args !! 0) | |
putStrLn $ "wolves: " ++ (args !! 1) | |
putStrLn $ "lions: " ++ (args !! 2) | |
let animalCount = map read args :: [Int] | |
doIt $ GWL (animalCount !! 0) (animalCount !! 1) (animalCount !! 2) | |
data GWL = GWL { goat :: !Int | |
, wolf :: !Int | |
, lion :: !Int} deriving (Eq, Ord, Show) | |
doIt :: GWL -> IO () | |
doIt m = doIt' (S.singleton m) | |
where | |
doIt' :: S.Set GWL -> IO() | |
doIt' ms = do | |
let newGWLs = eatAll ms | |
if S.foldl' setSuccess False newGWLs | |
then mapM_ print $ S.toList $ S.filter success $ newGWLs | |
else doIt' newGWLs | |
setSuccess :: Bool -> GWL -> Bool | |
setSuccess True _ = True | |
setSuccess False m = success m | |
success :: GWL -> Bool | |
success (GWL g w l) = (g == 0 && (w == 0 || l == 0)) || (w == 0 && l == 0) | |
eatAll :: S.Set GWL -> S.Set GWL | |
eatAll roundGWLs = S.foldl' eat S.empty roundGWLs | |
eat :: S.Set GWL -> GWL -> S.Set GWL | |
eat newEatSet (GWL g w l) = lionEatGoat | |
where | |
wolfEatGoat = if w > 0 && g > 0 | |
then S.insert (GWL (g-1) (w-1) (l+1)) newEatSet | |
else newEatSet | |
lionEatWolf = if w > 0 && l > 0 | |
then S.insert (GWL (g+1) (w-1) (l-1)) wolfEatGoat | |
else wolfEatGoat | |
lionEatGoat = if g > 0 && l > 0 | |
then S.insert (GWL (g-1) (w+1) (l-1)) lionEatWolf | |
else lionEatWolf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment