http://www.perlmonks.org?node_id=141069


in reply to (Golf) The Animal Game

i'm with redsquirrel; it's my second golf outing. i'm in with 183. obviously i'm not on the pro tour.

here's the full code:

#!/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 = <STDIN>) } $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 = <STDIN>) + } $ans =~ m/^y/io ? 1 : 0; }; # ask what animal, return user input sub t() { my $ans; while(!$ans) { print "\nwhat animal?\n"; chomp ($ans = <STDIN>) } $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 = <STDIN>); } $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" => ['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 i +f(g($y))}N:$b=i($u,$c=t);$q{$b}=[$u,$c];E:}
i have a commented version, with slightly better variable names...

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: } }
thanks for the fun.

~Particle