Skip to content

Instantly share code, notes, and snippets.

@jnareb
Created February 6, 2010 01:15
Show Gist options
  • Save jnareb/296446 to your computer and use it in GitHub Desktop.
Save jnareb/296446 to your computer and use it in GitHub Desktop.
mastermind-solver.pl, using Algorithm::Mastermind from CPAN
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use Algorithm::MasterMind::Partition_Worst;
use Term::ReadLine;
my $code_length = 4;
# W is for Water, A is for Wind
my @full_alphabet = qw(F L W E A R);
my $l = 4;
GetOptions('length|l=i' => \$l);
$l = @full_alphabet if $l > @full_alphabet;
my @alphabet = @full_alphabet[0..$l-1];
print "ALPHABET: ",@alphabet,"\n";
my $solver = Algorithm::MasterMind::Partition_Worst->new({
'alphabet' => \@alphabet,
'length' => $code_length,
});
my $first_string = $solver->issue_first();
print "GUESS: $first_string\n";
my ($blacks, $whites) = (0, 0);
my $term = Term::ReadLine->new('mastermind-solver');
$term->MinLine(undef); # do not include anything in history
TRY: {
do {
my $feedback = $term->readline('FEEDBACK> ');
last TRY if !defined $feedback;
($blacks, $whites) = split(/[,\/]/, $feedback);
last unless (defined $blacks && defined $whites);
print "RESULT $blacks/$whites\n";
last if $blacks == $code_length;
$solver->feedback({'blacks'=>$blacks,'whites'=>$whites});
my $played_string = $solver->issue_next();
print "GUESS: $played_string\n";
} while ($blacks < $code_length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment