Non repeating random numbers

As part of my project, I need to create non-repeating 2 or 3 digit random numbers by specifying a set of numbers. I do not want to implement a list or array for this, since I have to get 1 random number for each function call.

I tried to do this using the Java SecureRandom class. I got help from some sites, but I got stuck between them, can we shuffle VALUES and do it? But I do not know how to do this. Can someone 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);

     }
+5
source share
2 answers

Fisher-yates shuffling algorithm is the way to go. It is effective 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 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;
    }
+12

Manoj , , VALUES [], . : = 9 , ( ). = 8 VALUES [9] , Math.random() * 0 8. , VALUES [9] [9] , ( .. , ).

, :

for(int i=0; i <= VALUES.length - 1; i++){
        int rand = (int) (Math.random()*(VALUES.length-1));
        char temp = VALUES[i];
        VALUES[i] = VALUES[rand];
        VALUES[rand] = temp;

shuffle VALUES.length ( , ) - .

-2

All Articles