Skip to content

Instantly share code, notes, and snippets.

@RichardBarrell
Created October 23, 2014 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardBarrell/b8bc321ca507e8ff292b to your computer and use it in GitHub Desktop.
Save RichardBarrell/b8bc321ca507e8ff292b to your computer and use it in GitHub Desktop.
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