Universität Ulm, Fakultät für Mathematik und Wirtschaftswissenschaften, SAI

# Lösung zu Blatt 4 --- OO-Datenbank Anwendungen (WS 2002)

## Superhirn

```#!/usr/local/bin/perl -w

use strict;
use Getopt::Std;

my \$cmdname = \$0; \$cmdname =~ s{.*/}{};
my \$usage = "Usage: \$cmdname [-c colors] [-r rows]\n";
my %opts = (); getopts('c:r:', \%opts);
my \$rows = \$opts{'r'} || 4;
my \$colors = \$opts{'c'} || 6;
die \$usage if @ARGV >= 2;
if (\$colors >= 10 or \$colors < \$rows or \$rows < 1) {
die "At least one row and max. 10 colors\n";
}
my (\$black, \$white, \$input) = (0, 0);
my @result = gen(\$colors, \$rows);
my @guesses = ();
my %guesses = ();
print join("", @result), "\n";
until (\$black == \$rows) {
chomp(\$input = <>);
if (\$input =~ /^h/) {
print "History:\n", join("\n", @guesses), "\n";;
next;
}
if (defined \$guesses{\$input}) {
print "Den Versuch habe ich schon bewertet!\n";
next;
}
next unless test(\$colors, \$rows, \$input);
(\$black, \$white) = compare(\$input, @result);
print "Black: \$black, White: \$white.\n";
push @guesses, "\$input: Black: \$black, White: \$white.";
\$guesses{\$input} = 1;
}

sub test {
my (\$colors, \$rows, \$input) = @_;
if (length(\$input) != \$rows) {
print "Falsche Eingabe\n";
return 0;
}
my %guessed = ();
foreach (split //, \$input) {
unless (/^\d\$/ and \$_ < \$colors) {
print "Ungueltiger Rateversuch\n";
return 0;
}
if (defined \$guessed{\$_}) {
print "Doppelte Ziffer\n";
return 0;
}
\$guessed{\$_} = 1;
}
return 1;
}

sub compare {
my (\$guess, @res) = @_;
my %res = ();
my (\$black, \$white, \$pos) = (0, 0, 0);
foreach (@res) { \$res{\$_} = 1; }
foreach (split //, \$guess) {
if (\$_ == \$res[\$pos]) { \$black++}
elsif (defined \$res{\$_}) { \$white++; }
\$pos++;
}
return (\$black, \$white);
}

sub gen {
my (\$colors, \$rows) = @_;
my @res = ();
my %guessed = ();
my \$guess;
foreach (1 .. \$rows) {
do {
\$guess = int(rand \$colors);
} while defined \$guessed{\$guess};
push @res, \$guess;
\$guessed{\$guess} = 1;
}
return @res;
}
```

Ingo Melzer, 25. November 2002