<?xml version="1.0" encoding="windows-1252"?>
<node id="141069" title="Re: (Golf) The Animal Game" created="2002-01-23 22:29:06" updated="2005-07-21 01:30:39">
<type id="11">
note</type>
<author id="85567">
particle</author>
<data>
<field name="doctext">
i'm with [redsquirrel]; it's my second golf outing. i'm in with 183. obviously i'm not on the pro tour.&lt;p&gt;

here's the full code:&lt;p&gt;
&lt;code&gt;
#!/usr/local/bin/perl -w
use strict;
$|=1;

# www.PerlMonks.org 140734|(Golf) The Animal Game

# ask the question passed, return true or false
sub a($) {
	my ($qu, $ans) = (shift);
	while(!$ans) { print "\n$qu?\n"; chomp ($ans = &lt;STDIN&gt;) }
	$ans =~ m/y/io ? 1 : 0;
};

# ask if animal is passed value, return true or false
sub g($) {
	my ($ani, $ans) = (shift);
	while(!$ans) { print "\nis animal $ani?\n"; chomp ($ans = &lt;STDIN&gt;) }
	$ans =~ m/^y/io ? 1 : 0;
};

# ask what animal, return user input
sub t() {
	my $ans;
	while(!$ans) { print "\nwhat animal?\n"; chomp ($ans = &lt;STDIN&gt;) }
	$ans;
};

# get question to identify animal: 
# true for new, false for old; return question
sub i($$) {
	my ($old, $new, $qu) = (shift, shift);
	while(!$qu) {
		print "\nenter a question false for $old but true for $new:\n";
		chomp ($qu = &lt;STDIN&gt;);
	}
	$qu;
};

# ask to continue, return true or false
sub w() { a('play') ? 1 : exit 0 };

# question/answer data structure: hash of arrays
my %q = (
	"larger than a breadbox" =&gt; ['cat', 'giraffe'],
);

no strict;
while(w){($k,$v)=each%q;$k||redo;$u=$$v[a($k)];next if(g($u));while(($l,$x)=each%q){next unless$$x[0] eq $u;a($l)?$y=$$x[1]:goto N;goto E if(g($y))}N:$b=i($u,$c=t);$q{$b}=[$u,$c];E:}
&lt;/code&gt;

i have a commented version, with slightly better variable names...&lt;p&gt;
&lt;code&gt;
no strict;
{
	while(w){
		# select a question
		($k,$v)=each%q;
		# try again if no more questions (end of hash)
		$k||redo;
		# ask question, get proper animal from question hash
		$t2=$$v[a($k)];
		# guess animal, end loop if found answer
		next if(g($t2));
		# lookup keys with value[0] matching $t2
		while(($k2,$v2)=each%q){
			next unless$$v2[0] eq $t2;
			# if key exists, ask question
			# if answer negative, ask new animal
			a($k2)?$t5=$$v2[1]:goto NEW;
			goto END if(g($t5));
		}
		# else, ask new animal
NEW:
		# ask new animal
		$t4=i($t2,$t3=t);
		# add to question hash
		$q{$t4}=[$t2,$t3];
END:
	}
}
&lt;/code&gt;

thanks for the fun.&lt;p&gt;
&lt;P&gt;~Particle
</field>
<field name="root_node">
140734</field>
<field name="parent_node">
140734</field>
</data>
</node>
