选择具有特定范围的唯一随机数 [英] choose unique random numbers with specific range

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

问题描述

我的问题是我希望我的程序在0到3之间的数字范围内做出四个独特的随机选择我试着在随机类中进行,但我不能,如果你可以通过代码帮助它会很棒,我的程序将是这样的,以使其清楚

my problem is I want my program to make four unique random choices in range of numbers between 0 to 3 I tried to do it in random class but I could not, , if you could help by code it will be great,my program will be something like this to make it clear

my range

0 1 2 3  randomly chosen number 3

0 1 2    randomly chosen number 1

0 2      randomly chosen number 2

0        it will choose 0 and then the program closes


推荐答案

您正在有效地寻找整数的随机排列从 0 n-1

You're effectively looking for a random permutation of the integers from 0 to n-1.

你可以将 0 中的数字放入 n-1 ArrayList ,然后调用 Collections.shuffle() , n逐个从列表中获取数字:

You could put the numbers from 0 to n-1 into an ArrayList, then call Collections.shuffle() on that list, and then fetch the numbers from the list one by one:

    final int n = 4;
    final ArrayList<Integer> arr = new ArrayList<Integer>(n); 
    for (int i = 0; i < n; i++) {
        arr.add(i);
    }
    Collections.shuffle(arr);
    for (Integer val : arr) {
        System.out.println(val);
    }

Collectons.shuffle()保证所有排列都以相同的可能性发生。

Collectons.shuffle() guarantees that all permutations occur with equal likelihood.

如果您愿意,可以将其封装到 Iterable

If you wish, you could encapsulate this into an Iterable:

    public class ChooseUnique implements Iterable<Integer> {

        private final ArrayList<Integer> arr;

        public ChooseUnique(int n) {
            arr = new ArrayList<Integer>(n);
            for (int i = 0; i < n; i++) {
                arr.add(i);
            }
            Collections.shuffle(arr);
        }

        public Iterator iterator() {
            return arr.iterator();
        }
    }

当你迭代这个类的一个实例时,它产生随机排列:

When you iterate over an instance of this class, it produces a random permutation:

    ChooseUnique ch = new ChooseUnique(4);
    for (int val : ch) {
        System.out.println(val);
    }

在一次特定的运行中,打印出 1 0 2 3

On one particular run, this printed out 1 0 2 3.

这篇关于选择具有特定范围的唯一随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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