Skip to content

Commit df72a46

Browse files
authored
moo: distinct-digits rule was not followed
* 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
1 parent b5df2a2 commit df72a46

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

bin/moo

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,39 @@ License: perl
1111
1212
=cut
1313

14-
1514
use strict;
1615

17-
my ($VERSION) = '1.2';
16+
use List::Util qw(shuffle);
17+
18+
my ($VERSION) = '1.3';
1819

1920
sub usage {
2021
die "usage: moo [size]\n";
2122
}
2223

24+
sub has_dupe {
25+
my $guess = shift;
26+
my %chars;
27+
foreach my $c (split //, $guess) {
28+
return 1 if exists $chars{$c};
29+
$chars{$c} = 1;
30+
}
31+
return 0;
32+
}
33+
2334
my $size = shift;
2435
$size = 4 unless defined $size;
2536
usage() if $size !~ m/\A[0-9]+\Z/ or !$size;
2637
usage() if @ARGV;
2738

2839
print "MOO\n";
2940
{
30-
my @secret_by_value = (0) x 10;
31-
map {$secret_by_value [$_] ++} my @secret = map {int rand 10} 1 .. $size;
41+
my @secret = shuffle(0 .. 9);
42+
@secret = splice @secret, 0, $size;
43+
my @secret_by_value = (0) x 10;
44+
foreach my $i (@secret) {
45+
$secret_by_value[$i] = 1;
46+
}
3247

3348
my $attempts = 0;
3449

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

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

0 commit comments

Comments
 (0)