choose unique random numbers with specific range

徘徊边缘 提交于 2019-12-20 07:26:14

问题


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

回答1:


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

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() guarantees that all permutations occur with equal likelihood.

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);
    }

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




回答2:


You could fill an (if you don't need too many numbers) ArrayList<Integer> with numbers ranging from 0 - 3. Then you get a random index using Random.nextInt(list.size()), get the number from the list and removeAt the entry at your index.




回答3:


If you have your range in sometype of array, then just use a random over the length of the array.

For example if you have an int array called range. Then you could use:

java.utils.Random randomGenarator = new java.utils.Random();
return range[randomGenarator.nextInt(range.length)];


来源:https://stackoverflow.com/questions/9923781/choose-unique-random-numbers-with-specific-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!