生成2个数字之间的唯一的随机数 [英] Generating a unique random number between 2 numbers

查看:144
本文介绍了生成2个数字之间的唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关我的具体目的,我需要之间产生整数1和120包容性(这是我可以做的没问题)。

For my specific purposes, I need to generate a whole number between 1 and 120 inclusive (which I can do no problem).

在该号码已经产生,我需要从池中拉它,因此它不能被重新生成。

Once that number has been generated, I need to pull it from the pool so it can't be generated again.

继续这个过程,直到所有的数字都用尽,此时,池填满备份,我们重新开始。

Continue this process until all numbers are exhausted, at which point, the pool fills back up and we start over again.

我怎么能去这样做?

推荐答案

生成编号从1到120的整个列表随机播放列表。就拿第一个元素(和删除)

Generate the whole list of numbers from 1 to 120. Shuffle the list. Take the first element (and remove it)

List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 120; i++) {
    list.add(i)
}
Collections.shuffle(list);
...
int random = list.remove(0);
...
int otherRandom = list.remove(0);

为您在你用完了数字的情况下,list.empty()。如果为空,再创建列表,并将它洗。

Check for list.empty() in case you run out of numbers. If empty, create the list again and shuffle it.

这篇关于生成2个数字之间的唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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