Page 1 of 1

unique random numbers ruby array

Posted: Mon Sep 22, 2014 4:57 pm
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)?

Re: unique random numbers ruby array

Posted: Mon Sep 22, 2014 5:50 pm
by TheOm
There's probably a better way, but I would do

Code: Select all

(from..to).to_a.shuffle.take(size)

Re: unique random numbers ruby array

Posted: Mon Sep 22, 2014 6:23 pm
by tester
Should be fine, thanks. I just need to pick some random graphic files from folder, to get different results per each click.

Re: unique random numbers ruby array

Posted: Mon Sep 22, 2014 9:52 pm
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

Re: unique random numbers ruby array

Posted: Mon Sep 22, 2014 10:19 pm
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).

Re: unique random numbers ruby array

Posted: Mon Sep 22, 2014 11:30 pm
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.