Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generating non-repeating random numbers

I want to create a set of random numbers without duplicates in Java.

For example I have an array to store 10,000 random integers from 0 to 9999.

Here is what I have so far:

import java.util.Random; public class Sort{      public static void main(String[] args){          int[] nums = new int[10000];          Random randomGenerator = new Random();          for (int i = 0; i < nums.length; ++i){             nums[i] = randomGenerator.nextInt(10000);         }     } } 

But the above code creates duplicates. How can I make sure the random numbers do not repeat?

like image 744
Fernando Martinez Avatar asked Apr 14 '13 14:04

Fernando Martinez


People also ask

How do you generate a random Bounded number in Java?

nextBoolean() The nextDouble() and nextFloat() method generates random value between 0.0 and 1.0. The nextInt(int bound) method accepts a parameter bound (upper) that must be positive. It generates a random number in the range 0 to bound-1.


2 Answers

Integer[] arr = {...}; Collections.shuffle(Arrays.asList(arr)); 

For example:

public static void main(String[] args) {     Integer[] arr = new Integer[1000];     for (int i = 0; i < arr.length; i++) {         arr[i] = i;     }     Collections.shuffle(Arrays.asList(arr));     System.out.println(Arrays.toString(arr));  } 
like image 99
Achintya Jha Avatar answered Sep 21 '22 19:09

Achintya Jha


A simple algorithm that gives you random numbers without duplicates can be found in the book Programming Pearls p. 127.

Attention: The resulting array contains the numbers in order! If you want them in random order, you have to shuffle the array, either with Fisher–Yates shuffle or by using a List and call Collections.shuffle().

The benefit of this algorithm is that you do not need to create an array with all the possible numbers and the runtime complexity is still linear O(n).

public static int[] sampleRandomNumbersWithoutRepetition(int start, int end, int count) {     Random rng = new Random();      int[] result = new int[count];     int cur = 0;     int remaining = end - start;     for (int i = start; i < end && count > 0; i++) {         double probability = rng.nextDouble();         if (probability < ((double) count) / (double) remaining) {             count--;             result[cur++] = i;         }         remaining--;     }     return result; } 
like image 27
the Avatar answered Sep 19 '22 19:09

the