in reply to Re: generating random numbers within a range
in thread generating random numbers within a range

Thanks! Its a time waster, but it was driving me nuts...
Ted
--
"Men have become the tools of their tools."
  --Henry David Thoreau
  • Comment on Re^2: generating random numbers within a range

Replies are listed 'Best First'.
Re^3: generating random numbers within a range
by ikegami (Patriarch) on May 09, 2005 at 20:36 UTC

    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
      Very cool - Thats more along the lines of what humans would do. I like that one.
      Ted
      --
      "Men have become the tools of their tools."
        --Henry David Thoreau