In today’s Programming Praxis exercise, our goal is to solve two exercises from the MindCipher website (technically three, but the third one can be solved without programming). Let’s get started, shall we?
import Control.Monad import Data.List import System.Random
The first exercise is to see which pattern, on average, takes longer to come up when flipping a coin: heads, tails, heads or heads, tails, tails. First, we define a function to simulate single series of flips, counting the number of flips before the desired pattern is produced. Heads and tails are represented as booleans for the sake of convenience.
flipUntil :: [Bool] -> IO Int flipUntil pattern = fmap (length . takeWhile (not . isPrefixOf pattern) . tails . randomRs (False, True)) newStdGen
Next, we simulate an entire day by repeating this process 10000 times and taking the average.
day :: [Bool] -> IO Double day pattern = fmap (\cs -> fromIntegral (sum cs) / fromIntegral (length cs)) . replicateM 10000 $ flipUntil pattern
For the second exercise, we need to find the first year for which the sum of both groups of two digits is equal to the middle two digits. This is easily achieved via a simple brute-force search.
sumDay :: Maybe Integer sumDay = find (\d -> div d 100 + mod d 100 == div (mod d 1000) 10) [1979..]
Running our two algorithms shows that monday’s pattern takes longer on average and that the first year that satisfies the criteria is 2307.
main :: IO () main = do print =<< liftM2 compare (day [False, True, False]) (day [False, True, True]) print sumDay