Random integers
Author |
Message |
Clayton
|
Posted: Mon Feb 19, 2007 10:59 am Post subject: Random integers |
|
|
How would you manage this? I've been playing around in irb, and found rand(max), but I'd like to be able to have a defined range of numbers to randomize... Is there a pre-defined random integers method that does this, or would I have to create my own and seed it with the time or some such this? |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Cervantes
|
Posted: Mon Feb 19, 2007 2:14 pm Post subject: RE:Random integers |
|
|
You mean something like Rand.Int in Turing, where you provide a lower bound and a higher bound? Sure:
code: |
def rand_range(low, high)
rand(high - low) + low
end
|
|
|
|
|
|
|
Clayton
|
Posted: Mon Feb 19, 2007 4:37 pm Post subject: Re: Random integers |
|
|
hmm, I was thinking of something exactly like that, but I thought I had seen something wrong with it, and now that I think about it, I can't even remember what that was. Thanks Cervantes |
|
|
|
|
|
wtd
|
Posted: Mon Feb 19, 2007 11:25 pm Post subject: RE:Random integers |
|
|
code: | irb(main):012:0> class Range
irb(main):013:1> def random_choice
irb(main):014:2> rand(last - first) + first
irb(main):015:2> end
irb(main):016:1> end
=> nil
irb(main):017:0> (1..10).random_choice
=> 8
irb(main):018:0> (1..10).random_choice
=> 8
irb(main):019:0> (1..10).random_choice
=> 9
irb(main):020:0> (1..10).random_choice
=> 1
irb(main):021:0> (1..10).random_choice
=> 5
irb(main):022:0> |
|
|
|
|
|
|
Clayton
|
Posted: Mon Feb 19, 2007 11:38 pm Post subject: Re: Random integers |
|
|
Well, I've learned my bit of Ruby for the day. I had no idea there was a Range class. that's damn handy thanks wtd. |
|
|
|
|
|
|
|