for example my first set of results could be:
2, 8, 4, 6, 3, 10, 12, 1
the results need to be between 1 and 13 and they must be unique.
The rand(12) + 1 returns random numbers between 1 and 13, but they are
not unique. Any quick solutions?
--
Posted via http://www.ruby-forum.com/.
~$ irb
irb(main):001:0> (1..13).to_a.sort_by{rand}[0..7]
=> [7, 3, 8, 2, 11, 4, 1, 9]
irb(main):002:0>
--
RMagick: http://rmagick.rubyforge.org/
RMagick 2: http://rmagick.rubyforge.org/rmagick2.html
ar = []
while ar.length < 8
ar << rand(12) + 1
ar.uniq!
end
/Shawn
On Mon, Mar 24, 2008 at 6:00 PM, Jimmy Palmer <modern...@gmail.com>
wrote:
thanks Tim. i like it.
Here's one more possibility:
numbers = (1..13).to_a
randoms = []
8.times {randoms << numbers.delete_at(rand(numbers.size))}
Though, Tim's solution might be most readable.
Chris
You're welcome. Turns out you don't need the to_a. One less method.
(1..13).sort_by{ rand }.first(7)
my attempt to improve upon it :)
Tim's shuffle and cut technique seems fishy to me at first, but I like
it. Now I'll be up nights reading my old probability texts :)
Todd
You might also look through the solutions for Ruby Quiz #39 (Sampling).
http://rubyquiz.com/quiz39.html
there are couple of other ruby quizes where things like this are touched on.
You might browse through the archives.
enjoy,
-jeremy
--
========================================================================
Jeremy Hinegardner jer...@hinegardner.org
oh, i meant .first(8) ^^;
^ manveru
Hey Tim, I am a bit lost here :) sort_by accepts a block. But I see
you are just passing it a method. How does this work? Does Ruby
convert the return value of the method to a block and then sorts it?
Do you mind explaining it for me? Thanks so much.
--
http://ruby-smalltalk.blogspot.com/
---
Whereof one cannot speak, thereof one must be silent.
Ludwig Wittgenstein
Tim Hunter wrote:
> Jimmy Palmer wrote:
> > I'm trying to generate 8 unique random numbers ...
> > the results need to be between 1 and 13
> > and they must be unique.
>
> ~$ irb
> irb(main):001:0> (1..13).to_a.sort_by{rand}[0..7]
> => [7, 3, 8, 2, 11, 4, 1, 9]
For anyone still counting :), the following builds on Tim's approach:
(1..13).to_a.shuffle.first(8)
Array#shuffle is only available in ruby 1.9+ though.
Cheers, lasitha
--
View this message in context: http://www.nabble.com/generating-unique-random-numbers-tp16266148p16322324.html
Sent from the ruby-talk mailing list archive at Nabble.com.