Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non repeating random numbers

Tags:

java

random

As a part of my project I need to create non repeating 2 or 3 digit random numbers by giving a set of numbers. I don't want to implement a list or array for that, since I should get 1 random number for each function call.

I tried to do that using SecureRandom class of Java. I got help from some of the sites as well, but I am stuck in between, can we shuffle the VALUES and get it done? But I don't know how that could be done. Can anyone help me?

import java.security.SecureRandom;
public class RandomNumber {
private static final RandomNumber rnd= new RandomNumber();

    private static final char[] VALUES = new char[] {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};  
     private static final SecureRandom srn= new SecureRandom();
     public String createID()
     { 
       byte[] bytes = new byte[3]; 
       srn.nextBytes(bytes);

     }
like image 406
vidhya Avatar asked Feb 04 '11 11:02

vidhya


People also ask

What is the most Randomest number?

At the end of the survey, the number that appeared most frequently was 17, causing it to be dubbed “the most random number” (http://en.wikipedia.org/wiki/17_(number)).

Do random number generators repeat?

The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes. The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed.

Why is RNG not random?

Random number generators are typically software, pseudo random number generators. Their outputs are not truly random numbers. Instead they rely on algorithms to mimic the selection of a value to approximate true randomness.


1 Answers

Fisher-yates shuffle algorithm is the way to go. Its efficient for shuffling. and it works in linear time.

here is algo

To shuffle an array a of n elements:
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]

and the code

for(int i=VALUES.length-1; i>0; i--){
            int rand = (int) (Math.random()*i);
            char temp = VALUES[i];
            VALUES[i] = VALUES[rand];
            VALUES[rand] = temp;
    }
like image 115
Manoj Avatar answered Nov 11 '22 06:11

Manoj