Created
September 3, 2010 20:05
-
-
Save prakashk/564473 to your computer and use it in GitHub Desktop.
24-game in Perl 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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