2

I want to create a method that will generate random and unique numbers from 0 to 999. What I've tried to do is to generate random unique numbers and then add them to a vector so that each time i call the method it will generate a random number and then compare it to the previously generated numbers and see if it's unique. If it's not, the process is repeated. Thats the idea but every time i run the program i get "array index out of range: 0".

I have initialized the vector at the beginning of the class as private Vector<Integer> uniqueNums;

public int returnRandom() {
        Random r = new Random();
        int rand = r.nextInt(10000);

        if(this.uniqueNums.capacity() != 0) {
            for(int i = 0; i < this.uniqueNums.capacity(); i++) {
                if(rand == this.uniqueNums.get(i))
                    returnRandom();
            }
        }
        this.uniqueNums.add(rand);
        return rand;
    }
4
  • 1
    Easy way to do this is to add the integers from 0 to 999 to a List, and the call Collections.shuffle to randomize the elements. Then you can remove items from the head or tail of the list to get unique random numbers. Commented Apr 6, 2020 at 23:36
  • Does this answer your question? best way to pick a random subset from a collection? Commented Apr 6, 2020 at 23:37
  • @dnault what's wrong with the way im trying to do it? Commented Apr 6, 2020 at 23:49
  • 1
    @JohnEm — the way you're doing it now, you pick a random number and search the list to see if that number's in it; if it is you have to pick again. That's ok to start, but imagine when you've used nearly all the numbers. Say you only have 2 spots left to fill, and the only 2 numbers you haven't used are 117 and 842… you pick a random from 0 to 999, you search the 998 member list, and you will probably already have used that number, so you pick again; well you've probably used that one too, so you pick again, and again, and again. Filling those last 2 slots could take a very long time. Commented Apr 7, 2020 at 0:35

1 Answer 1

1

It looks as if you have declared uniqueNums, but not assigned any value to it. The array index is out of range of a null. Try initializing it to some empty value and see if that helps.

Regardless, this seems like an odd way to create 'unique randoms'. I would go with dnault's suggestion.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried to add 2 initial values and what happened was that the "array index out of range: 0" changed to "array index out of range: 1"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.