1

I am doing something where I have to choose a couple random numbers, without choosing the same number again. I have tried many ways, but they will not work. I checked if the random number exists in my int[], and reset the int to another random, but what is that other random also exists, I tried fixing that but I ran into problems.

Here's my current code:

p.sendMessage("debug over max");
        Random r = new Random();
        for (int i=0;i<max + 1;i++) {
            int ran = r.nextInt(arenaAmount);
            if (ran == 0) ran = 1;
            arenas[i] = ran;
        }

Thats what I have so far, so how can I make sure it doesn't have the same number. If there is another thread already please link me to it.

Thanks, Joey.

Beta Nyan
  • 25
  • 2

3 Answers3

1

A simple solution would be to add the already generated numbers to a Set and generate random numbers until you hit one that isn't already in that Set.

But that's probably not a very good solution, check the accepted answer here for a thorough explanation.

As mentioned by Giovanni Botta in the comments, here's another simple solution that's probably better than the Set based one.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

make a arenas a Set

Random r = new Random(); 
int ran = r.nextInt(); 
while( ! arenas.add(ran) ) {
   ran = r.nextInt(); 
}

add will fail on an attempted re-entry of a value.

corn3lius
  • 4,857
  • 2
  • 31
  • 36
0

You could create a list of integers from 1 to maxValue, shuffle it and get the numElements first elements:

List<Integer> shuffledList(int maxValue, int numElements) {
    if (numElements >= maxValue) {
        throw new IllegalArgumentException("The number of elements in the list must be less than maxValue.");
    }
    List<Integer> numbers = range(1, maxValue);
    Collections.shuffle(numbers);
    return numbers.subList(0, numElements);
}

List<Integer> range(int from, int to) {
    List<Integer> numbers = new ArrayList<>(to - from);
    for (int i = from; i < to; i++) {
        numbers.add(i);
    }
    return numbers;
}

This way, you are sure to get different numbers without the Set overhead. Making a call like shuffledList(10, 5) would, for example, return a list like [8, 7, 5, 1, 2], with 5 elements, where the smallest possible element is 1 and the greatest possible element is 9.

Also, if you are using Java 8 you can discard the range function and do this instead:

List<Integer> numbers = IntStream.range(1, maxValue)
                                 .boxed()
                                 .collect(Collectors.toList());
Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48