user
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.
assistant
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
use MONKEY-SEE-NO-EVAL;

say "Here are your digits: ", 
constant @digits = (1..9).roll(4)».Str;
 
grammar Exp24 {
    token TOP { ^ <exp> $ { fail unless EVAL($/) == 24 } }
    rule exp { <term>+ % <op> }
    rule term { '(' <exp> ')' | <@digits> }
    token op { < + - * / > }
}
 
while my $exp = prompt "\n24? " {
    if try Exp24.parse: $exp {
        say "You win :)";
        last;
    } else {
        say (
            'Sorry.  Try again.' xx 20,
            'Try harder.' xx 5,
            'Nope.  Not even close.' xx 2,
            'Are you five or something?',
            'Come on, you can do better than that.'
        ).flat.pick
    }
}

```

The `MONKEY-SEE-NO-EVAL` pragma enables the dangerous `EVAL` function, which will compile and execute even user input. In this example, the grammar used to parse the input should ensure that only safe expressions are evaluated.