Instead of trying to generate a list of unique random numbers, why don't you generate a range of numbers and shuffle that list?
Generate unique integer in range using Faker gem [closed]
-
30-07-2021 - |
Question
This seems like it should be simple but I can't find an answer anywhere!
I'm building a sample_data rake file in Rails to populate my db using the Faker gem. (though I don't think I need that gem for just generating integers)
Some of the fields need to be an integer within a set range but each must be unique. For instance:
10.times do |a|
a.special_number = rand(1..10)
end
works well except for the fact that the numbers aren't unique...
La solution
Autres conseils
I would suggest to use hash rather than array, because the complexity to compare a number in Array is array.length while in hash it's 1. And you can finally transfer hash keys into an array.
hash = {} r = [ ]
while hash.length < n
a = rand(max)
if !hash_has_key? (a)
hash(a) = :ok
end
end
r = hash.keys
if you test n=30000 and max = 500000, the time consumed is very different compared with using array.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow