Duplicate:
I want an pseudo random number generator that can generate numbers with no repeats in a random order.
For example:
random(10)
might return 5, 9, 1, 4, 2, 8, 3, 7, 6, 10
Is there a better way to do it other than making the range of numbers and shuffling them about, or checking the generated list for repeats?
Edit:
Also I want it to be efficient in generating big numbers without the entire range.
Edit:
I see everyone suggesting shuffle algorithms. But if I want to generate large random number (1024 byte+) then that method would take alot more memory than if I just used a regular RNG and inserted into a Set until it was a specified length, right? Is there no better mathematical algorithm for this.
Shuffling N elements doesn't take up excessive memory...think about it. You only swap one element at a time, so the maximum memory used is that of N+1 elements.
Suppose you wanted to generate a series of 256 random numbers without repeats.
b
n
, the number of numbers yet to be generatedn = 256
ton = 1
r
in the range[0, n)
r
-th zero bit in your memory blockb
, let's call itp
p
in your list of results, an array calledq
p
-th bit in memory blockb
to1
n = 1
pass, you are done generating your list of numbersHere's a short example of what I am talking about, using
n
= 4 initially:I asked a similar question before but mine was for the whole range of a int see Looking for a Hash Function /Ordered Int/ to /Shuffled Int/
If you don't mind mediocre randomness properties and if the number of elements allows it then you could use a linear congruential random number generator.
Actually, there's a minor point to make here; a random number generator which is not permitted to repeat is not random.
now we have a array with different numbers!