This is a holdover from Friday - it was a slow day, and this is how my idle time was spent.
The code below is supposed to generate a random number from a range of numbers provided and then pick another random number and stick that in a different variable. For each guess that it makes its supposed to return too high or too low and then make a new range between low and high. It dies this sort of - but it doesnt always seem to stay within the new range for new guesses. This is probably the 5th or 6th revision of the script - Ive tried a few different variations of the code.
use strict;
my $low = 1;
my $high = 10;
my @range=($low .. $high);
my $rand=int(rand(@range));
my $seed=-1;
my $count=1;
my $lastguess;
while ( $seed != $rand )
{
undef @range if ( $ count > 1);
@range=($low .. $high);
$lastguess = $seed;
$seed = int(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";
Im just not seeing what is wrong. any help is appreciated
Ted
--
"Men have become the tools of their tools."
--Henry David Thoreau
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.