How to generate n different random numbers within a specified interval in java
Implementation method:
First define an array with a length of n, and then start using a while loop to generate random numbers to assign values to the array. Before assigning values, you need to traverse the array. Existing values, if the values are equal, regenerate random numbers without assigning values, and loop until all defined arrays are assigned.
Examples are as follows:
/** * 功能:产生min-max中的n个不重复的随机数 * * min:产生随机数的其实位置 * mab:产生随机数的最大位置 * n: 所要产生多少个随机数 * */ public static int[] randomNumber(int min,int max,int n){ //判断是否已经达到索要输出随机数的个数 if(n>(max-min+1) || max <min){ return null; } int[] result = new int[n]; //用于存放结果的数组 int count = 0; while(count <n){ int num = (int)(Math.random()*(max-min))+min; boolean flag = true; for(int j=0;j<count;j++){ if(num == result[j]){ flag = false; break; } } if(flag){ result[count] = num; count++; } } return result; }
Java learning video recommendation:Introduction to java development
Using the characteristics of Set, elements cannot be repeated
/** * 功能:随机指定范围内N个不重复的数 * * @param min 指定范围最小值 * @param max 指定范围最大值 * @param n 随机数个数 */ public static int[] randomSet(int min, int max, int n) { Set<Integer> set = new HashSet<Integer>(); int[] array = new int[n]; for (; true;) { // 调用Math.random()方法 int num = (int) (Math.random() * (max - min)) + min; // 将不同的数存入HashSet中 set.add(num); // 如果存入的数小于指定生成的个数,则调用递归再生成剩余个数的随机数,如此循环,直到达到指定大小 if (set.size() >= n) { break; } } int i = 0; for (int a : set) { array[i] = a; i++; } return array; }
First put the generated random number into the set, and then determine the size of the set. If it does not exceed the required length, continue the loop. If it has exceeded, jump out of the loop and convert the set into an array.
More java related article recommendations: Java language introduction
The above is the detailed content of How to generate n different random numbers within a specified interval in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft