Archive for November, 2009

Programming Praxis – $7.11

November 27, 2009

Today’s Programming Praxis problem is an easy one.  We’re supposed to give the prices of four items, that both sum up and multiply to $7.11. Let’s get started.

While we could just do a brute force test on all possible combinations, this would take rather long. So in order to speed things up we only check numbers that are a proper divisor of $7.11.

divs :: [Int]
divs = [x | x <- [1..711], mod (711 * 10^6) x == 0]

Once we have the divisors, solving the problem becomes a fairly trivial list comprehension (the <= bits are another optimization to eliminate some identical combinations).

main :: IO ()
main = print [(a,b,c,d) | a <- divs,         b <- divs, b <= a,
                          c <- divs, c <= b, d <- divs, d <= c,
                          a + b + c + d == 711,
                          a * b * c * d == 711 * 10^6]

If we run this, we find there is only one combination that satisfies both requirements.

Programming Praxis – Master Mind, Part 1

November 17, 2009

…aaaand we’re back. Sorry for the delay, life can get really busy. In yesterday’s Programming Praxis problem we have to create a program that will answer guesses for the game Master Mind. Let’s get to it, shall we?

As usual, some imports:

import Data.List
import System.Random

First, we need a function to determine how good the player’s guess was:

match :: [Int] -> [Int] -> String
match code guess = concat $ zipWith replicate [bs, ws, ds] "BW."
    where bs = length . filter id $ zipWith (==) code guess
          ds = length (foldr delete code guess)
          ws = length code - bs - ds

Next, we write the guess loop:

go :: [Int] -> IO ()
go code = do hits <- fmap (match code) readLn
             if all (== 'B') hits then putStrLn "You Win!"
                else putStr (hits ++ "\nTry again: ") >> go code

A game can be started either with a predefined code or a random one if none has been provided.

play :: Maybe [Int] -> IO ()
play code = do putStr "Enter your guess as a list: "
               rnd <- fmap (take 4 . randomRs (1, 8)) getStdGen
               go $ maybe rnd id code

To test, start a game with a random code:

main :: IO ()
main = play Nothing

And that’s it for this week. Have fun playing!