mercredi 27 avril 2016

Take always a different random element in range

I need to select two different integers that belong to a certain range [min, max].

Example: rds = 3, min = 0, max = 9. If the first random element is r1 = 6, then r2 must be different from 6 and r3 must be different from r1 and 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 and 9 with return ThreadLocalRandom.current().nextInt(0, 10) and then I swap r1 and the last element of the array. To find r2 I apply the random function from 0 to the penultimate position in the array, and so on.

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] but a random number in the contents of an array.

Thanks.




Aucun commentaire:

Enregistrer un commentaire