Course of Raku / Addendum 🆕 / Flow and functions / Control flow and logic / Exercises / Rock, paper, scissors
Solution: Rock, paper, scissors
Here is a possible solution to the task.
Code
my %beats = rock => 'scissors', scissors => 'paper', paper => 'rock';
sub winner($a, $b) {
return 'tie' if $a eq $b;
return %beats{$a} eq $b ?? "$a wins" !! "$b wins";
}
for <rock scissors>, <paper rock>, <paper paper> -> ($a, $b) {
say "$a vs $b: { winner($a, $b) }";
}🦋 You can find the source code in the file rock-paper-scissors.raku.
Output
rock vs scissors: rock wins
paper vs rock: paper wins
paper vs paper: tieComments
The
%beatshash encodes the rules: each move maps to the move it defeats. That turns judging into a single lookup instead of a long chain of conditions.If
%beats{$a}is the opponent’s move, then$awins; otherwise (equal moves already handled)$bwins.