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;
    }
JohnEm
  • 29
  • 5
  • 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. – dnault Apr 06 '20 at 23:36
  • Does this answer your question? [best way to pick a random subset from a collection?](https://stackoverflow.com/questions/136474/best-way-to-pick-a-random-subset-from-a-collection) – dnault Apr 06 '20 at 23:37
  • @dnault what's wrong with the way im trying to do it? – JohnEm Apr 06 '20 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. – Stephen P Apr 07 '20 at 00:35

1 Answers1

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.

jcklopp
  • 451
  • 5
  • 9
  • 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" – JohnEm Apr 07 '20 at 09:59