Generating Unique Random Numbers Effectively in Java

Generating Unique random numbers effectively in Java

You could create a set of random integers like this:

Set<Integer> set = new HashSet<Integer>();
Random rand = new Random();

while (set.size() < 10) {
set.add(rand.nextInt((1000000)));
}

The idea is that the set data structure will remove duplicates.

Generating unique random numbers

Following are two possible approaches :-

Method 1 :-

  1. Have all numbers in an array with size n.
  2. select a number an index at random i = rand(0,size)
  3. print arr[i]
  4. swap arr[i] and arr[size-1]
  5. size = size -1
  6. repeat 1 to 5 till list is exhausted.

Time Complexity: O(N)

Space Complexity: O(N)

Method 2:-

  1. Select a pool size of K.
  2. generate K random integers.
  3. show them as first k results.
  4. Add them to a hashset.
  5. Add all ak+1 for all previous integers in a pool.
  6. Add 1 if it is not in hashset.
  7. pick a integer r at random from pool and show it .
  8. Add r+1 into pool if its not in hashset
  9. Do 7 to 8 till pool is exhausted.

Time complexity: O(N)

Space complexity: O(K)

Pro & Cons :-

Method 1: Use this method for small integer ranges as it requires larger space but it is very fast and random.

Method 2: Use this method for larger ranges as it takes memory O(K) which is of your choice. The higher the k the higher is the randomness in the numbers generated. So you can achieve a nice trade off between space and randomness with maintaining good speed.

Generating Unique Random Numbers in Java

  • Add each number in the range sequentially in a list structure.
  • Shuffle it.
  • Take the first 'n'.

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

The first part of the fix with the original approach, as Mark Byers pointed out in an answer now deleted, is to use only a single Random instance.

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.

What is optimal way to get four unique random number from 0-9?

You can use Collections.shuffle:

// generate a List that contains the numbers 0 to 9
List<Integer> digits = IntStream.range(0,10).boxed().collect(Collectors.toList());
// shuffle the List
Collections.shuffle (digits);
// take the first 4 elements of the List
int numbers[] = new int[4];
for(int i=0;i<4;i++){
numbers[i] = digits.get(i);
}

How to create unique random numbers from a given Random generator

The idea is to use the Random generator given to compute the required random numbers.

1) For random numbers 1-20, just divide the 100 numbers equally to represent 1 to 20.

2) To generate 1-200, find the even numbers from 1 to 200 and then add (-1 or 0) to it to get all the numbers from 1 to 200.

import java.util.*;
public class Rand20_200{
int number20[]=new int[20]; //numbers in random order
int number200[]=new int[200];

public Rand20_200(){
int n=0;
int ngen[]=new int[20]; //to store which random numbers are generated
while(n<20){
int rnd=1 + (getrand100()-1) / 5;
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number20[n++]=rnd;
}
}
System.out.println("Random 20 numbers");
print(number20);

ngen=new int[200]; //to store which random numbers are generated
int numoff[]={-1,0}; //offset to add
n=0;
while(n<200){
int rnd=numoff[(getrand100()-1)/50]+ (getrand100()*2);
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number200[n++]=rnd;
}
}
System.out.println("\nRandom 200 numbers");
print(number200);
}

int getrand100(){
Random rand = new Random();
return (1+rand.nextInt(100));
}

void print(int arr[]){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}

public static void main(String args[]){
new Rand20_200();
}

}

Generate set of unique random numbers in Java

Make a LinkedList of the numbers from 1-500 and shuffle one out of them each time you use a number using The Fisher-Yates shuffle.

This will give you guaranteed sane (constant time) performance for each number pulled.

How to generate unique random numbers in an array

Try this:

import java.util.Random;

public class random {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random myRandom = new Random();
int[] numbers = new int[50];
boolean[] check = new boolean[50];
int amountFilled = 0;
int trial;
while (amountFilled < 50) {
trial = myRandom.nextInt(50);
if (!check[trial]) {
check[trial] = true;
numbers[amountFilled] = trial;
amountFilled++;
}
}
for (int i = 0; i < 50; i++) {
System.out.println(numbers[i]);
}
}
}

Your real problem was the System.out.println(nums); statement. It doesn't do what you what it to do. And the double Random rand=new Random();. The rest of the code is OK. I rewrote it in a clearer/simpler way, but what you had already works if you fix the output statement.

Creating unique random numbers in Java

    HashSet<Integer> set = new HashSet<Integer>();
Random random = new Random();
int i = 0;

while(set.size() < 10){
set.add(random.nextInt(40) + 1);
i++;
}

System.out.println(set);
System.out.println(i);


Related Topics



Leave a reply



Submit