I am required to create a program that creates 10 unique numbers from 0(incl) to 10(excl) in java but so far mine repeats some numbers. what is the best way i can implement this?
Code so far..... (forgive my code, i'm still a bit new to java)
public static int[] UniqueRand (int N)
{
//Create a list of random numbers
int [] randNums = new int[N];
Random numRandom = new Random();
for (int i = 0; i < N; i++){
randNums[i] = numRandom.nextInt(N);
}
return randNums;
}
Main Function: (generally (n) could be any range not just 10)
public static void main(String [] args)
{
int n = 10;
Random newRandom = new Random();
int [] randNums = UniqueRand(n);
int [] replace = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println();
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if (randNums[i] == randNums[j]){
for (int k = 0; k < 10; k++){
if (randNums[i] != replace[k]) randNums[i] = replace[k];
}
}
}
}
}
Output would be: [9, 1, 5, 9, 0, 2, 4, 6, 1, 9]