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.


final random = new Random()
final input = new Scanner(System.in)
 
 
def evaluate = { expr ->
    if (expr == 'QUIT') {
        return 'QUIT'
    } else {
        try { Eval.me(expr.replaceAll(/(\d)/, '$1.0')) }
        catch (e) { 'syntax error' }
    }
}
 
 
def readGuess = { digits ->
    while (true) {
        print "Enter your guess using ${digits} (q to quit): "
        def expr = input.nextLine()
 
        switch (expr) {
            case ~/^[qQ].*/:
                return 'QUIT'
 
            case ~/.*[^\d\s\+\*\/\(\)-].*/:
                def badChars = expr.replaceAll(~/[\d\s\+\*\/\(\)-]/, '')
                println "invalid characters in input: ${(badChars as List) as Set}"
                break
 
            case { (it.replaceAll(~/\D/, '') as List).sort() != ([]+digits).sort() }:
                println '''you didn't use the right digits'''
                break
 
            case ~/.*\d\d.*/:
                println 'no multi-digit numbers allowed'
                break
 
            default:
                return expr
        }
    }
}
 
 
def digits = (1..4).collect { (random.nextInt(9) + 1) as String }
 
while (true) {
    def guess = readGuess(digits)
    def result = evaluate(guess)
 
    switch (result) {
        case 'QUIT':
            println 'Awwww. Maybe next time?'
            return
 
        case 24:
            println 'Yes! You got it.'
            return
 
        case 'syntax error':
            println "A ${result} was found in ${guess}" 
            break
 
        default:
            println "Nope: ${guess} == ${result}, not 24"
            println 'One more try, then?'
    }
}