在Ruby中生成非重复随机数 [英] Generate non-repeating random numbers in Ruby

查看:209
本文介绍了在Ruby中生成非重复随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个介于100和999之间的唯一随机数序列.我想确保没有两次生成任何数字,以确保每个数字都是唯一的.这是我想出的.这没用.当我运行它时,屏幕只是空白.谁能帮我吗?

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)

推荐答案

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

然后每次您需要新的ID

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.

这篇关于在Ruby中生成非重复随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆