My endless quest for diversions caused me to write this Mastermind game knockoff. Maybe should be Monkmind?...
Search revealed only one implementation, [68803|here], so I thought I'd offer this alternative.
YuckFoo
#!/usr/bin/perl
use strict;
my $DIGITS = 6;
print "\nFind the $DIGITS digit number:\n\n";
print "* = Right digit, right position.\n";
print "+ = Right digit, wrong position.\n";
my $code = sprintf("%*.*d", $DIGITS, $DIGITS, int(rand(10**$DIGITS)));
my (@trys, $try, $inp, $i);
while ($try->{guess} ne $code) {
print "\nGuess: ";
chomp($inp = <>);
$try = {};
push (@trys, $try);
$try->{guess} = $inp;
$try->{score} = score($inp, $code);
print "\n";
for ($i = 0; $i < @trys; $i++) {
$try = $trys[$i];
printf (STDOUT "%3d %-*.*s %s\n",
$i+1, $DIGITS, $DIGITS, $try->{guess}, $try->{score});
}
}
#-----------------------------------------------------------
sub score {
my ($gues, $code) = @_;
my @codes = split('', $code);
my @guess = split('', $gues);
my ($str, $i, %codes, @retry);
# check for number in right position
for ($i = 0; $i < @codes; $i++) {
if ($codes[$i] eq $guess[$i]) {
$str .= '*';
}
else {
$codes{$codes[$i]}++;
push (@retry, $guess[$i]);
}
}
# check for number in wrong position
for $i (@retry) {
if ($codes{$i}-- > 0) { $str .= '+'; }
}
return $str;
}