unique random numbers ruby array

For general discussion related FlowStone
Post Reply
tester
Posts: 1786
Joined: Wed Jan 18, 2012 10:52 pm
Location: Poland, internet

unique random numbers ruby array

Post by tester »

I know I have it somewhere, but can't find it.

How to quickly create in ruby - an array of specified size (how many items), made of unique random numbers (integers) in specified range (from..to)?
Need to take a break? I have something right for you.
Feel free to donate. Thank you for your contribution.
TheOm
Posts: 103
Joined: Tue Jan 28, 2014 7:35 pm
Location: Germany

Re: unique random numbers ruby array

Post by TheOm »

There's probably a better way, but I would do

Code: Select all

(from..to).to_a.shuffle.take(size)
tester
Posts: 1786
Joined: Wed Jan 18, 2012 10:52 pm
Location: Poland, internet

Re: unique random numbers ruby array

Post by tester »

Should be fine, thanks. I just need to pick some random graphic files from folder, to get different results per each click.
Need to take a break? I have something right for you.
Feel free to donate. Thank you for your contribution.
billv
Posts: 1165
Joined: Tue Aug 31, 2010 3:34 pm
Location: Australia
Contact:

Re: unique random numbers ruby array

Post by billv »

Sounds like you won't need this tester, but I will add it for sake of the 'thread title".
The array version of my Urn module will ensure every element remains unique
and non-repeating with every shuffle.
http://www.dsprobotics.com/support/viewtopic.php?f=3&t=2380#p14120
tester
Posts: 1786
Joined: Wed Jan 18, 2012 10:52 pm
Location: Poland, internet

Re: unique random numbers ruby array

Post by tester »

What's wrong with what TheOm provided? It works, it's single line, and is resistant to borderline situations as far I can see (pool size vs declaration array size).
Need to take a break? I have something right for you.
Feel free to donate. Thank you for your contribution.
billv
Posts: 1165
Joined: Tue Aug 31, 2010 3:34 pm
Location: Australia
Contact:

Re: unique random numbers ruby array

Post by billv »

tester wrote:What's wrong with what TheOm provided?

Where did i say it was wrong?
Like i said tester..
billv wrote:Sounds like you won't need this tester, but I will add it for sake of the 'thread title"

As I wrote, the behaviour of my Urn array is different, and might be useful for someone
who see's this thread title, and seeking a alternative option.
Post Reply