Skip to content

Instantly share code, notes, and snippets.

@prakashk
Created September 3, 2010 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prakashk/564473 to your computer and use it in GitHub Desktop.
Save prakashk/564473 to your computer and use it in GitHub Desktop.
24-game in Perl 6
# From: http://rosettacode.org/wiki/24_game
#
# The 24 Game tests one's mental arithmetic.
#
# Write a program that randomly chooses and displays four digits, each
# from one to nine, with repetitions allowed. The program should
# prompt for the player to enter an equation using just those, and all
# of those four digits. The program should check then evaluate the
# expression. The goal is for the player to enter an expression that
# evaluates to 24.
#
# * Only multiplication, division, addition, and subtraction
# operators/functions are allowed.
#
# * Division should use floating point or rational arithmetic,
# etc, to preserve remainders.
#
# * If using an infix expression evaluator then brackets are
# allowed.
#
# * 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.
grammar Exp24 {
token TOP { ^ <exp> $ }
token exp { <term> [ <op> <term> ]* }
token term { '(' <exp> ')' | \d }
token op { '+' | '-' | '*' | '/' }
}
my @digits = map { (1..9).pick }, 1..4;
say "Here's your digits: {@digits}";
while my $exp = prompt "\n24-Exp? " {
unless is-valid($exp, @digits) {
say "Sorry, your expression is not valid!";
next;
}
my $value = eval $exp;
say "$exp = $value";
if $value == 24 {
say "You win!";
last;
}
say "Sorry, your expression doesn't evaluate to 24!";
}
sub is-valid($exp, @digits) {
unless ?Exp24.parse($exp) {
say "Expression doesn't match rules!";
return False;
};
unless $exp.comb(/\d/).sort.join == @digits.sort.join {
say "Expression must contain digits {@digits} only!";
return False;
}
return True;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment