Skip to content

Commit

Permalink
moo: distinct-digits rule was not followed (#933)
Browse files Browse the repository at this point in the history
* The unix version of moo selects a number where each digit occurs only once in the number [1]
* A guess containing non-unique digits is not a valid guess [2]
* Add a function to check for duplicate digits in guess
* Rewrite secret number generator with shuffle() to guarantee unique digits


1. http://squoze.net/UNIX/v6man/man6/moo.pdf
2. https://github.com/hansklav/MOO
  • Loading branch information
mknos authored Jan 27, 2025
1 parent b5df2a2 commit 5c0679f
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions bin/moo
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,39 @@ License: perl
=cut


use strict;

my ($VERSION) = '1.2';
use List::Util qw(shuffle);

my ($VERSION) = '1.3';

sub usage {
die "usage: moo [size]\n";
}

sub has_dupe {
my $guess = shift;
my %chars;
foreach my $c (split //, $guess) {
return 1 if exists $chars{$c};
$chars{$c} = 1;
}
return 0;
}

my $size = shift;
$size = 4 unless defined $size;
usage() if $size !~ m/\A[0-9]+\Z/ or !$size;
usage() if @ARGV;

print "MOO\n";
{
my @secret_by_value = (0) x 10;
map {$secret_by_value [$_] ++} my @secret = map {int rand 10} 1 .. $size;
my @secret = shuffle(0 .. 9);
@secret = splice @secret, 0, $size;
my @secret_by_value = (0) x 10;
foreach my $i (@secret) {
$secret_by_value[$i] = 1;
}

my $attempts = 0;

Expand All @@ -39,7 +54,7 @@ print "MOO\n";
chomp (my $guess = <>);
exit if (!defined($guess) || $guess =~ m/\Aq/i);

if ($guess =~ /\D/ || length $guess != $size) {
if ($guess =~ /\D/ || length $guess != $size || has_dupe($guess)) {
print "Bad guess\n";
redo
}
Expand Down Expand Up @@ -99,7 +114,7 @@ moo [size]
=head1 DESCRIPTION
I<moo> is a game where the user guesses a random number chosen by
the computer. By default, the computer takes a number of four digits
the computer. By default, the computer takes a number of four distinct digits
(including 0's), but that can be changed by giving I<moo> the number of
digits to take. After each guess, the number of B<bull>s and B<cow>s
is displayed. A B<bull> is a correctly guessed digit, in the right
Expand Down

0 comments on commit 5c0679f

Please sign in to comment.