marielle - 7 months ago 10

Java Question

I need to select two different integers that belong to a certain range

`[min, max]`

`rds = 3`

`min = 0`

`max = 9`

`r1 = 6`

`r2`

`6`

`r3`

`r1`

`r2`

I thought of building an array containing all the numbers belonging to

`[min, max]`

`[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`

I select a random number between

`0`

`9`

`ThreadLocalRandom.current().nextInt(0, 10)`

`r1`

To find

`r2`

`0`

This is the code:

`public void takeRandomXposition(int rds, int[] positions) {`

int k = positions.length;

int min = 0;

int max = k - 1;

for(int i = 0; i < rds; i++) {

int r = random(positions[min], positions[max - i]);

swapPositions(positions, r, max - i);

}

}

public int random(int min, int max) {

return ThreadLocalRandom.current().nextInt(min, max + 1);

}

public void swapPositions(int[] positions, int index, int last) {

int indexA = positions[index];

int lastA = positions[last];

positions[index] = lastA;

positions[last] = indexA;

}

This method works for the first steps, but not anymore.

The problem is that the elements in the array are moved and mixed, but I try the random number in a range.

I don't know how to explain, I give an example in which the method doesn't work.

`positions: [ 0 1 2 3 4 5 6 7 8 9 ]`

rds = 3

k = 10

min = 0

max = 9

i = 0

search r in range [0, 9]

r = 5

positions: [ 0 1 2 3 4 9 6 7 8 5 ]

i = 1

search r in range [0, 8]

r = 3

positions: [ 0 1 2 8 4 9 6 7 3 5 ]

i = 2

search r in range [0, 7]

r = 5

positions: [ 0 1 2 8 4 7 6 9 3 5 ]

In addition there is also a problem when

`r = 0`

`positions: [ 0 1 2 3 4 5 6 7 8 9 ]`

rds = 3

k = 10

min = 0

max = 9

i = 0

search r in range [0, 9]

r = 0

positions: [ 9 1 2 3 4 5 6 7 8 0 ]

i = 1

search r in range [9, 8]

Exception in thread "main" java.lang.IllegalArgumentException: bound must be greater than origin

So, I don't want to find a random number in a range

`[min, max]`

Thanks.

Answer

Store your generated random numbers in a list and keep generating until you find one which is not in the list.

```
LinkedList<Integer> list = new LinkedList<>();
final int min = 0;
final int max = 10;
while(list.size() < max) // Condition to not keep iterating forever
{
do
{
int random = ThreadLocalRandom.current().nextInt(min, max + 1);
} while (list.contains(random));
list.add(random);
}
```

You can also use an approach with arrays, as you were trying to do

```
int min = 0;
int max = 10;
int array[] = new int[max + 1];
int filledArray = 0;
while(filledArray < max + 1) // Condition to not keep iterating forever
{
do
{
int random = ThreadLocalRandom.current().nextInt(min, max + 1);
} while (array[random] == 1);
array[random] = 1;
filledArray++;
}
```

EDIT: Im not completly sure if this is what you are looking for. What I understood is that you want to find random numbers in a given range without getting twice the same random number

Source (Stackoverflow)

Comments