Reputation: 71
randomized = 10.times.map { Random.new.rand(1..100) }
I wanted to make 10 randomized numbers that do not repeat twice. How do I check it? I don't want to do the long one such as
puts randomized[0] != randomized[1]
puts randomized[1] != randomized[2]
Upvotes: 0
Views: 60
Reputation: 80085
Array#sample takes an argument:
randomized = (1..100).to_a.sample(10) #=> [52, 100, 92, 93, 33, 66, 78, 84, 36, 98]
From the docs: " The elements are chosen by using random and unique indices into the array in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements."
Upvotes: 6
Reputation: 988
You could just shuffle and array of the given set to guarantee no dups.
randomized = (1..100).to_a.shuffle
You can then just pop them off
next_r = randomized.pop
Upvotes: 2