在 Java 中生成唯一的随机数 [英] Generating Unique Random Numbers in Java

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

问题描述

我正在尝试获取 0 到 100 之间的随机数.但我希望它们是唯一的,而不是按顺序重复.例如,如果我有 5 个数字,它们应该是 82,12,53,64,32 而不是 82,12,53,12,32我用过这个,但它按顺序生成相同的数字.

I'm trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32 and not 82,12,53,12,32 I used this, but it generates same numbers in a sequence.

Random rand = new Random();
selected = rand.nextInt(100);

推荐答案

  • list 结构.
  • 随机播放.
  • 取第一个n".
  • 这是一个简单的实现.这将打印 1-10 范围内的 3 个唯一随机数.

    Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class UniqueRandomNumbers {
        
        public static void main(String[] args) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            for (int i=1; i<11; i++) {
                list.add(i);
            }
            Collections.shuffle(list);
            for (int i=0; i<3; i++) {
                System.out.println(list.get(i));
            }
        }
    }
    


    正如 Mark Byers 在现已删除的答案中指出的那样,原始方法修复的第一部分是仅使用单个 Random 实例.

    这就是导致数字相同的原因.Random 实例按当前时间(以毫秒为单位)播种.对于特定的种子值,随机"实例将返回完全相同的伪随机数字序列.

    That is what is causing the numbers to be identical. A Random instance is seeded by the current time in milliseconds. For a particular seed value, the 'random' instance will return the exact same sequence of pseudo random numbers.

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

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