Tuesday, July 18, 2017

Generate unique random numbers in java without using in build function

Pseudo code to generate unique random number :

a) Add entries in an array of size n.
b) Put an maxIndex on last value of array.
c) Find random index from 0 to maxIndex.
d) Swap array[random] and array[maxIndex]
e) maxIndex--

f) This way we get random number and we're putting random number in last of the array and subtracting size of array.

package com.corejava;

/* @Description- Class Generating unique random Generator
 * @author- Paras
 * */

public class RandomUniqueGenerator {
     static int maxI;
     static int uniqueArray[]= new int[11];
     public static void main(String[] args) {
          /* Create an array of 0 to 10 number*/
          for(int i=0;i<=10;i++)
              uniqueArray[i]=i;
         
          /*maxI denotes last index*/
          maxI=uniqueArray[uniqueArray.length-1];
         
          while(maxI>=0){
              /* pick any random index */
              int randomIndex = (int)(Math.random()*maxI);
              System.out.println("Index comes out to be "+ randomIndex);
              System.out.println("Random number found to be "+ uniqueArray[randomIndex]);
              swap(randomIndex);
     };
     }
     static void swap(int index){
          /*swap array[r] and array[maxI]*/
          int temp=uniqueArray[maxI];
          uniqueArray[maxI]=uniqueArray[index];
          uniqueArray[index]=temp;
          maxI--;
     }
}

Output

Index comes out to be 5
Random number found to be 5
Index comes out to be 7
Random number found to be 7
Index comes out to be 6
Random number found to be 6
Index comes out to be 2
Random number found to be 2
Index comes out to be 5
Random number found to be 10
Index comes out to be 0
Random number found to be 0
Index comes out to be 2
Random number found to be 9
Index comes out to be 1
Random number found to be 1
Index comes out to be 1
Random number found to be 3
Index comes out to be 0
Random number found to be 8
Index comes out to be 0
Random number found to be 4


No comments:

Post a Comment