diff options
| author | Mark A <andemark@a-iot1t.uch.ad.pvt> | 2021-03-17 01:09:50 -0600 |
|---|---|---|
| committer | Mark A <andemark@a-iot1t.uch.ad.pvt> | 2021-03-17 01:09:50 -0600 |
| commit | cd9ca137d40b3f56994bf7c5befaaaeb6b5ccde5 (patch) | |
| tree | c12c08ac43c4f11b6ef33e94c72b1bd9b84e21c0 /challenge-104/mark-anderson | |
| parent | 02dd2d3b8c7d2af3d2fdadeebbdad1bafc0f0036 (diff) | |
| download | perlweeklychallenge-club-cd9ca137d40b3f56994bf7c5befaaaeb6b5ccde5.tar.gz perlweeklychallenge-club-cd9ca137d40b3f56994bf7c5befaaaeb6b5ccde5.tar.bz2 perlweeklychallenge-club-cd9ca137d40b3f56994bf7c5befaaaeb6b5ccde5.zip | |
Challenge 104 Solutions (Raku)
Diffstat (limited to 'challenge-104/mark-anderson')
| -rw-r--r-- | challenge-104/mark-anderson/raku/ch-2.raku | 78 |
1 files changed, 53 insertions, 25 deletions
diff --git a/challenge-104/mark-anderson/raku/ch-2.raku b/challenge-104/mark-anderson/raku/ch-2.raku index fb217a4902..13db1b9aa3 100644 --- a/challenge-104/mark-anderson/raku/ch-2.raku +++ b/challenge-104/mark-anderson/raku/ch-2.raku @@ -3,37 +3,65 @@ # with help from # https://www.futurelearn.com/info/courses/recreational-math/0/steps/43529 -my $heap = 12; -my @players = <Human Machine>.rotate(<0 1>.pick); +role machine-play +{ + method play($heap) + { + $heap mod 4 || (1..min(3, $heap)).pick; + } +} + +role human-play +{ + method play($heap) + { + my $tokens = 0; + + while $tokens !~~ 1..min(3, $heap) + { + $tokens = prompt("How many: "); + } + + $tokens; + } +} -say "{@players.head} chooses first\n"; +class player +{ + has $.name; +} -loop +class nim { - last unless $heap; - say "heap = $heap\n"; - my $player = @players.head; + has $.heap is rw; + has @.players; - my $tokens = do + method play { - if $player eq "Machine" - { - $heap mod 4 || (1..min(3, $heap)).pick; - } - else + say @.players.head.name ~ " chooses first\n"; + + loop { - my $tokens = 0; - - while $tokens !~~ 1..min(3, $heap) - { - $tokens = prompt("How many: "); - } - - $tokens; + last unless $.heap; + say "heap = $.heap\n"; + my $player = @.players.head; + my $tokens = $player.play($.heap); + say "{$player.name} chose $tokens\n"; + $.heap -= $tokens; + @.players .= rotate(1); } + + say @.players.tail.name ~ " is the winner"; + } + + submethod TWEAK + { + self.players .= rotate(<0 1>.pick); } - - say "$player chose $tokens\n"; - $heap -= $tokens; - @players .= rotate(1); } + +my $h = player.new(name => "Human") but human-play; +my $m = player.new(name => "Machine") but machine-play; +my $nim = nim.new(heap => 12, players => [$h, $m]); + +$nim.play; |
