Bulls and cows: Difference between revisions

1,066 bytes removed ,  12 years ago
Undoing my Perl script -- there was already one on the page, only with a typo in the markup
(Undoing my Perl script -- there was already one on the page, only with a typo in the markup)
Line 1,844:
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
}</lang>
 
=={{header|Perl}}==
 
<lang perl>
use 5.10.0;
 
use strict;
 
use List::Util qw/ shuffle sum /;
use List::MoreUtils qw/ any uniq pairwise /;
 
my $size = 4;
 
# pick the secret number
my @secret = (shuffle 1..9)[0..$size-1];
 
say 'I have chosen a number of ', $size,
' unique digits from 1 to 9 arranged in a random order.';
say 'You need to input a ', $size,
' digit, unique digit number as a guess at what I have chosen';
 
my $nbr_attempts = 1;
 
GUESS:
while ( 1 ) {
 
print "Next guess [$nbr_attempts]: ";
 
chomp ( my $guess = <> );
 
my @guess = split '', $guess;
 
say 'you need to enter ', $size, ' unique digits, from 1 to 9. Try again'
and redo GUESS
if $guess !~ /^[1-9]{$size}$/ or @guess > uniq @guess;
 
my $bulls = sum pairwise { $a == $b } @guess, @secret;
 
last GUESS if $bulls == $size;
 
my $cows = sum( map { $_ ~~ @secret } @guess ) - $bulls;
 
say " $bulls Bulls";
say " $cows Cows";
 
$nbr_attempts++;
}
 
say "Congratulations, you guessed correctly in $nbr_attempts attempts";
</lang>
 
 
=={{header|Perl 6}}==
Anonymous user