Random Unique Generation logic-
a) Pick any random index from [0-n] array
b) Fetch value from array[random]
c) Swap value to last array[last]
/*
@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 3
Random number found to be 3
Index comes out to be 3
Random number found to be 9
Index comes out to be 5
Random number found to be 10
Index comes out to be 2
Random number found to be 2
Index comes out to be 2
Random number found to be 6
Index comes out to be 3
Random number found to be 8
Index comes out to be 2
Random number found to be 7
Index comes out to be 1
Random number found to be 1
Index comes out to be 0
Random number found to be 0
Index comes out to be 0
Random number found to be 4
No comments:
Post a Comment