Best way to create a list of unique random numbers in Java

preview_player
Показать описание
*Input:
a range in [A, B]
* Output:
a list of unique random numbers from A to B
* For example:
generateRandomNumbers(5, 15)

then output is: 11 13 5 14 12 9 6 8 7 15 10
Рекомендации по теме
Комментарии
Автор

after a long search i find an
thanks a
keep rocking like this

rtamilselvim.e.
Автор

Hello, in this case the problem that the first case of array "result" result[0] can't contain the last value of a[x-1]
perhaps, we need a random array ?

bensmidahoussemeddine
Автор

If I want to get 5 unique random numbers between 20 and 30, it gives unique random numbers from 20 to 24. I should get 27 or 28 etc but this program doesn't give that. There is a bug in it.

shorem
Автор

the bug fix for numbers out of range:
for(int i = 1; i <= n; i++)
{
a[i - 1] = i;
}

// an array to store the result
int[] result = new int[n];

SecureRandom rd = new SecureRandom();
int x = n;
for(int i = 1; i <= n; i++)

{
// k is a random index in [0, x]
int k = rd.nextInt(x);

result[i - 1] = a[k];

a[k] = a[x - 1];

x--;
}

markogilo
Автор

i dont get how
a[k] = a[x-1];
x--; will make no duplicate.

Say generateRandomNumbers(0, 5)

int k = 3;
a[3] = a[6-1]; //a[3] = 5
x--; //x = 5
// now it loop
int k = 3; //what prevent this from happening?

I see it work, but I don, t understand, please explain.

jintsuubest
Автор

You gave the lower limit 4 and upper limit 15, why it gives random numbers less than 4. It should give random numbers equal to or greater than 4 and less than or equal to 15. But it gives numbers less than the lower limit which is 4.

shorem
Автор

same code is generating duplicate values also

gurugovindgarg
Автор

how can i make this start from 1 not from zero?

glennviola
visit shbcf.ru