Created
October 23, 2014 13:32
-
-
Save RichardBarrell/b8bc321ca507e8ff292b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module FindBirthday where | |
-- compile as: ghc --make FindBirthday.hs -main-is FindBirthday.main | |
-- or run as: runhaskell FindBirthday.hs | |
-- and answer "y" or "n" when the program asks you a question. :) | |
import Data.Time (formatTime, addDays) | |
import System.Locale (defaultTimeLocale) | |
-- use 2014 because that was a leap year, and we need all 366 days. | |
showNthDay :: Integer -> String | |
showNthDay n = formatTime defaultTimeLocale "%d %B" . addDays n . read $ "2004-01-01" | |
main :: IO () | |
main = guess 256 0 | |
guess :: Integer -> Integer -> IO () | |
guess 0 a = putStrLn $ "Your birthday is " ++ showNthDay a | |
guess n a | n + a > 365 = guess (n `div` 2) a | |
guess n a | True = do | |
let candidate = n+a | |
putStrLn $ "Is your birthday on or after " ++ showNthDay candidate ++ "?" | |
reply <- getLine | |
let a' = if take 1 reply == "y" then candidate else a | |
guess (n `div` 2) a' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment