2

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.

Dave Yarwood
  • 2,866
  • 1
  • 17
  • 29
rainstop3
  • 1,408
  • 11
  • 13

3 Answers3

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