Generate non-repeating random numbers in Ruby

2019-05-24 12:28发布

问题:

I want to generates a sequence of unique random number between 100 and 999. I want to make sure that no numbers are generated twice, to ensure that each number is unique. Here is what I came up with. It does not work. When i run it, the screen is just blank. Can anyone help me?

products = {}

def random_key(products)

  rand_key = rand(900) + 100

  while products.has_key?(rand_key)

    rand_key = rand(900) + 100

  end

end

puts random_key(products)

回答1:

a = (100..999).to_a.shuffle 

then every time you need a new id

new_id = a.pop

This guarantees that numbers are never reused. Of course, you'll have problems when you run out of elements on the array.



回答2:

Notice that the last statement in your method is the while loop, which will not execute if products is empty. Hence function returns nil.

Try like this:

products = {}

def random_key(products)

  rand_key = rand(900) + 100

  while products.has_key?(rand_key)

    rand_key = rand(900) + 100

  end

  rand_key

end

puts random_key(products)

Note however, that this has a potential of getting into an infinite loop once all numbers from 100 to 999 are in products



回答3:

Your function returns the while expression which is always nil. You should return the number instead:

def random_key(products)
  rand_key = rand(900) + 100
  while products.has_key?(rand_key)
    rand_key = rand(900) + 100
  end
  rand_key
end

Note that you can remove duplication by placing "while" after key generation:

def random_key(products)
  begin
    rand_key = rand(900) + 100
  end while products.has_key?(rand_key)
  rand_key
end

And you can omit begin end for a single expression

def random_key(products)
  rand_key = rand(900) + 100 while products.has_key?(rand_key)
  rand_key
end


标签: ruby random