在Java中生成一组唯一的随机数 [英] Generate set of unique random numbers in Java

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

问题描述

我想在0-500范围内创建10个随机数。但问题是我希望这些数字是唯一的。对于2个随机数,我可以创建如下内容:

I want to create 10 random numbers in the range 0-500. But the problem is that I want those numbers to be unique. For 2 random numbers i could create something as the following:

int randomItem1 = r.nextInt(500);
int randomItem2 = r.nextInt(500);
while(randomItem1==randomItem2){
    randomItem1=randomItem();
    randomItem2=randomItem();
}

但如果我这样做10,我认为它会叠加。而我这样说是因为我正在尝试创建一个巨大的算法,试图进行持续的评估,我想要不断地获取10个随机和唯一的数字。我不知道该怎么办。有什么想法或建议吗?

But if I do this for 10, I think that the while it will stack. And I'm saying this because I'm trying to create a huge algorithm which is trying to make continuous evaluations and i want continously to take 10 random and unique numbers. I don't know what to do. Any ideas or suggestions?

推荐答案

从中提取 LinkedList 每次使用 Fisher-时,每次使用数字时,请将1-500个随机播放耶茨洗牌

这将为每个拉出的数字提供有保证的理智(恒定时间)表现。

This will give you guaranteed sane (constant time) performance for each number pulled.

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

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