The 24 Game tests one's mental arithmetic.



Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.

The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.

The goal is for the player to enter an expression that (numerically) evaluates to 24.

 Only the following operators/functions are allowed: multiplication, division, addition, subtraction
 Division should use floating point or rational arithmetic, etc, to preserve remainders.
 Brackets are allowed, if using an infix expression evaluator.
 Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
 The order of the digits when given does not have to be preserved.


Notes
 The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
 The task is not for the program to generate the expression, or test whether an expression is even possible.


Related tasks
 24 game/Solve


Reference
 The 24 Game on h2g2.


import Data.List (sort)
import Data.Char (isDigit)
import Data.Maybe (fromJust)
import Control.Monad (foldM)
import System.Random (randomRs, getStdGen)
import System.IO (hSetBuffering, stdout, BufferMode(NoBuffering))
 
main = do
  hSetBuffering stdout NoBuffering
  mapM_
    putStrLn
    [ "THE 24 GAME\n"
    , "Given four digits in the range 1 to 9"
    , "Use the +, -, *, and / operators in reverse polish notation"
    , "To show how to make an answer of 24.\n"
    ]
  digits <- fmap (sort . take 4 . randomRs (1, 9)) getStdGen :: IO [Int]
  putStrLn ("Your digits: " ++ unwords (fmap show digits))
  guessLoop digits
  where
    guessLoop digits =
      putStr "Your expression: " >> fmap (processGuess digits . words) getLine >>=
      either (\m -> putStrLn m >> guessLoop digits) putStrLn
 
processGuess _ [] = Right ""
processGuess digits xs
  | not matches = Left "Wrong digits used"
  where
    matches = digits == (sort . fmap read $ filter (all isDigit) xs)
processGuess digits xs = calc xs >>= check
  where
    check 24 = Right "Correct"
    check x = Left (show (fromRational (x :: Rational)) ++ " is wrong")
 
-- A Reverse Polish Notation calculator with full error handling
calc xs =
  foldM simplify [] xs >>=
  \ns ->
     (case ns of
        [n] -> Right n
        _ -> Left "Too few operators")
 
simplify (a:b:ns) s
  | isOp s = Right ((fromJust $ lookup s ops) b a : ns)
simplify _ s
  | isOp s = Left ("Too few values before " ++ s)
simplify ns s
  | all isDigit s = Right (fromIntegral (read s) : ns)
simplify _ s = Left ("Unrecognized symbol: " ++ s)
 
isOp v = elem v $ fmap fst ops
 
ops = [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))]