Hmm.. not the most efficient algorithm by any means. It works, certainly. I'm not trying to rag on Uman, but there are other ways. Most notably, instead of filling the entire array and checking for duplicates at the end, pick each number individually. Also, use a second array to check for collisions instead of using nested for-loops. (Nested loops run in n-squared time, while an array method would run in constant time.. sorta).
public static int getRandom(int min, int max) {
return ((int) (Math.random() * (max - min + 1))) + min;
}
public static void fillArray(int[] toFill) {
boolean[] beenUsed = new boolean[46];
for (int i = 0; i < 45; i++) {
beenUsed[i] = false;
}
//for each element in the array to me filled
for (int j = 0; j < toFill.length; j++) {
//find a number that's not been used yet
int ran;
do {
ran = getRandom(1, 45);
} while (beenUsed[ran]);
//put that number in the toFill array, and mark it used in the beenUsed array
toFill[j] = ran;
beenUsed[ran] = true;
}
}
If you're wondering, the boolean array is in fact one size larger than it really needs to be. I could have make it one size smaller and subtraced all values by one, but this way's easier to understand. And before anyone gets on my case over my sacrificing memory efficiency for speed efficienfy, just know that I always favor speed. *shrugs*