Skip to content

Instantly share code, notes, and snippets.

@jeek
Created October 5, 2009 09:51
Show Gist options
  • Save jeek/202018 to your computer and use it in GitHub Desktop.
Save jeek/202018 to your computer and use it in GitHub Desktop.
a mastermind solver
#!/usr/bin/perl
sub generate {
return int(rand() * 6 + 1) . int(rand() * 6 + 1) . int(rand() * 6 + 1) . int(rand() * 6 + 1);
}
$solution=generate();
for ($x1 = 1 ; $x1 < 7 ; $x1++) {
for ($x2 = 1 ; $x2 < 7 ; $x2++) {
for ($x3 = 1;$x3 < 7;$x3++) {
for ($x4 = 1 ; $x4 < 7 ; $x4++) {
$possible{"$x1$x2$x3$x4"}=1;
}
}
}
}
$guess="1111";
while (evaluate($guess,$solution) ne "BBBB") {
$matches=evaluate($guess,$solution);
print "$guess $matches " . (scalar keys %possible) . " \n";
foreach $possible (keys %possible) {
if (evaluate($guess,$possible) ne $matches) {
delete $possible{$possible};
}
}
$guess=(sort keys %possible)[0];
}
print "$guess " . evaluate($guess,$solution) . "\n";
sub evaluate {
my $guess=shift; my $solution=shift;
my $black=0;
my $white=0;
my $result="";
for ($i=0;$i<4;$i++) {
if (substr($solution,$i,1) eq substr($guess,$i,1)) {
$result.="B";
substr($guess,$i,1)="0";
substr($solution,$i,1)="0";
}
}
for ($i = 1 ; $i <= 6; $i++) {
$result .= "W"x(min($solution =~ s/$i//g,$guess =~ s/$i//g));
}
return $result;
}
sub min {
my $i=eval shift;
my $j=eval shift;
return ($i < $j) ? $i : $j;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment