use strict; use warnings; my $low = 1; my $high = 10; my @range=($low .. $high); my $rand=$range[rand(@range)]; # <--- my $seed=$low-1; # <--- Works for all values of $low and $high. my $count=1; my $lastguess; while ( $seed != $rand ) { #undef @range if ( $ count > 1); # <--- Useless. @range=($low .. $high); $lastguess = $seed; $seed = $range[rand(@range)]; # <--- if ( $seed < $rand ) { print "You're too low - $seed (last guess = $lastguess)\n"; $low=$seed+1; $count++; } elsif ( $seed > $rand ) { print "you're too high - $seed (last guess = $lastguess)\n"; $high=$seed-1; $count++; } } print "you got it in $count tries\n"; print "seed = $seed rand = $rand ( last guess = $lastguess )\n"; #### use strict; use warnings; my $low = 1; my $high = 10; my $range = $high - $low + 1; my $rand = $low + int(rand($range)); my $count = 0; for (;;) { my $guess = $low + int(rand($range)); $count++; print("$count) Guessing $guess."); last if $guess == $rand; if ( $guess < $rand ) { print " Too low.\n"; $low = $guess + 1; } elsif ( $guess > $rand ) { print " Too high.\n"; $high = $guess - 1; } $range = $high - $low + 1; } if ($count == 1) { print " Got it on the first try!\n"; } else { print " Got it in $count tries.\n"; }