I need to generate an array of int values for a given size, the values should be random and unique. the following implementation is "ok" for small values [1,10k]
, I would like to get some feedback on better implementation
/**
* Generate an array of random & unique values in the interval [0,desiredSize*3]
* To use only for small arrays with size in [1,50k]
* for an array of 1k time: 0.01s
* for an array of 10k time: 0.3s
* for an array of 50k time: 8s
* @param desiredSize
* @return
*/
public int[] generateRandAndUniq(int desiredSize) {
int[] arrayResult = new int[desiredSize];
Random rand = new Random();
arrayResult[0]= rand.nextInt(desiredSize);
int counter = 0;
while (counter < desiredSize) {
int randValue = rand.nextInt(desiredSize*3);/* a larger interval! */
int[] tempArray= new int[counter+2];
System.arraycopy(arrayResult, 0, tempArray,0, counter);
tempArray[counter+1]=randValue;
if(!checkDuplicate(tempArray)){
arrayResult[counter]=randValue;
counter++;
}
}
return arrayResult;
}
public boolean checkDuplicate(int[] arr) {
boolean[] bitmap = new boolean[maxValueInArray(arr)+1]; /* just put a big number to avoid looping to get the max value? */
for (int v : arr) {
if (!bitmap[v]) {
bitmap[v] = true;
} else {
return true;
}
}
return false;
}
public int maxValueInArray(int[] arr){
int max=-1;
for(int v:arr){
if(v>max)
max=v;
}
return max;
}