I have this code -
number1, number2, number3, number4, number5 = Array.new(5) { rand(99999)+1 }
How can I make sure that each number is unique? Also - is it possible to output all numbers as 5 digit? Like 00147 instead of 147?
Thanks for help!
I have this code -
number1, number2, number3, number4, number5 = Array.new(5) { rand(99999)+1 }
How can I make sure that each number is unique? Also - is it possible to output all numbers as 5 digit? Like 00147 instead of 147?
Thanks for help!
list = []
(list << '%05i' % (rand(99999)+1)).uniq! while list.length < 5
number1, number2, number3, number4, number5 = list
def get_unique_random(n)
a = []
while n > 0 do
r = "%05d" % (rand(99999)+1)
(a << r; n -= 1) unless a.include?(r)
end
a
end
get_unique_random(5)
[Edit: I fixed an error I had introduced with an edit. (Ever done that?) Previously I had:
r = rand(99999)+1;
(a << "%05d" % r; n -= 1) unless a.include?(r)
I will leave it as an exercise to spot the error.]
This seems like the simplest approach to me. Each number is guaranteed to be unique.
array = (1...99999).to_a
unique_randoms = 5.times.map { '%05i' % array.delete_at(rand(array.length)) }