Home > Java > JavaBase > How to generate random unique numbers in java

How to generate random unique numbers in java

Release: 2019-12-05 11:51:33
Original
3145 people have browsed it

How to generate random unique numbers in java

How to generate random non-repeating numbers in java:

Generate n non-repeating random numbers based on min and max. (Note: Range [min,max], n <= (max - min 1))

Idea:

0), put all possible numbers from min to max Enter a candidate List;

1), randomly generate index index (0 <= index <= (list.size()-1));

2), based on index Take a number from the List, list.get(index), and remove the element;

The code is as follows:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MyRandom {

    /**
     * 根据min和max随机生成一个范围在[min,max]的随机数,包括min和max
     * @param min
     * @param max
     * @return int
     */
    public int getRandom(int min, int max){
        Random random = new Random();
        return random.nextInt( max - min + 1 ) + min;
    }

    /**
     * 根据min和max随机生成count个不重复的随机数组
     * @param min
     * @param max
     * @param count
     * @return int[]
     */
    public int[] getRandoms(int min, int max, int count){
        int[] randoms = new int[count];
        List<Integer> listRandom = new ArrayList<Integer>();

        if( count > ( max - min + 1 )){
            return null;
        }
        // 将所有的可能出现的数字放进候选list
        for(int i = min; i <= max; i++){
            listRandom.add(i);
        }
        // 从候选list中取出放入数组,已经被选中的就从这个list中移除
        for(int i = 0; i < count; i++){
            int index = getRandom(0, listRandom.size()-1);
            randoms[i] = listRandom.get(index);
            listRandom.remove(index);
        }

        return randoms;
    }
}
Copy after login

Java Math.random() method is used to return a random number, random The range of numbers is 0.0 =< Math.random < 1.0.

For more java knowledge, please pay attention to java basic tutorial.

The above is the detailed content of How to generate random unique numbers in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template