I want to generate 5 different random numbers. I have generated a range from 0 to 100. I want to pick 5 numbers from the range randomly.
Asked
Active
Viewed 633 times
3 Answers
5
You can generate a list of n unique random numbers in Ruby like this:
(1..99).to_a.sample(5)
=>[69, 50, 15, 68, 29]

scottxu
- 913
- 1
- 7
- 20
1
a = []
while true
a << rand(101) # if you want to get 100
break if a.uniq.count == 5
end
it can get 5 different random number.

pangpang
- 8,581
- 11
- 60
- 96
-1
You can also try something like this:
arr = []
(1..5).each{|t| arr << rand(100)}
arr
#=> [78, 19, 34, 96, 59]
This array may contain repeated elements as pointed out by @p11y in comments.
Here's the fix to that (inspired by his comments):
a = 5.times.map { rand(100) }
until a.uniq.size==5 do
a += (5-a.uniq.size).times.map{rand (100)}
end
a.uniq!
I think there are better solutions already posted here, this is just an alternative answer.

shivam
- 16,048
- 3
- 56
- 71
-
1This can produce the same number twice, the OP asked for "5 different random numbers". – Patrick Oscity Aug 22 '14 at 07:09
-
1Also, you could just write `5.times.map { rand(100) }` – Patrick Oscity Aug 22 '14 at 07:10
-
@p11y thanks for teaching me that. I have updated my answer. Though its still not elegant, I guess it should work fine now. scottxu's solution is much better. – shivam Aug 22 '14 at 07:30
-
1+1 to this solution for taking the `5.times.map { rand(100) }` idea and finding an interesting way to make sure the results are unique. – Dave Yarwood Aug 22 '14 at 21:10