-3

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]

  • "10 unique random numbers from 1 to 10 without repeats" - could you give a sample? – Pavel Smirnov Sep 12 '20 at 22:12
  • There is only one sequence of numbers from 0 to 10 (including 0 and excluding 10) that doesn't have any repeated numbers: 0 1 2 3 4 5 6 7 8 9. For other values where more than one sequence is possible, I'm afraid you'll have to check for any repeated values and substitute them, repeating the substitution until all values are unique. – JustAnotherDeveloper Sep 12 '20 at 22:12
  • 1
    If the number must be positive integers , as you seem to assume, it means your numbers will necessarily be 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. The only randomness left is to choose their ordering. – dbaltor Sep 12 '20 at 22:13
  • Loop with i = 0 - N. Choose a random integer r from 0-N. Swap replace[i] and replace[r]. Done. – NomadMaker Sep 12 '20 at 23:52

1 Answers1

1

There are 2 ways to do this sort of problem, each with advantages. You can generate any number and see if it is used, great at first and horrible at the end You can build a list of all candidates and remove them as they are used, generating a selector index of the size of the remaining list until the size is 1. The latter might be in an array but removing intermediate members means moving the rest of the list, but a linked list means traversing the list to find the nth member.

for big lists, start with method 1 and switch to method 2 at some point, like 80% used or so!

Generating integers 0 to N is a simple math problem. Make sure you are getting truly random choices! A float/double random is nice as a starting point.