in reply to Re^2: generating random numbers within a range
in thread generating random numbers within a range
By the way, if you want to guess the number in a guaranteed maximum number of guesses, divide the search space into two instead of randomly guessing.
Change
my $guess = $low + int(rand($range));
to
my $guess = $low + int($range/2);
to see this in action. You'll find the number of guesses is never more than ceil(log2(range)) guesses. This is called a binary search.
ceil(log2(x)) ------------- 1.. 8: 3 1.. 16: 4 1.. 32: 5 1.. 64: 6 1.. 128: 7 1.. 256: 8 1.. 512: 9 1.. 1024: 10 1.. 10: 4 1.. 100: 7 1.. 1,000: 10 1.. 10,000: 14 1.. 100,000: 17 1.. 1,000,000: 20 1..10,000,000: 24
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: generating random numbers within a range
by tcf03 (Deacon) on May 09, 2005 at 20:40 UTC |