Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Random Number Sequence with No Repeats

Duplicate:

Unique random numbers in O(1)?

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.

like image 898
Unknown Avatar asked Mar 29 '09 00:03

Unknown


People also ask

How do you make Excel randomly select from a list without repeats?

Only works in Excel 365 and Excel 2021 that support dynamic arrays. To select random rows with no repeats, build a formula in this way: INDEX(SORTBY(data, RANDARRAY(ROWS(data))), SEQUENCE(n), {1,2,…}) Where n is the sample size and {1,2,…} are column numbers to extract.

How do you find a non repeating random number?

Pick a random number, r, between 0 and max, swap the number at the position r with the number at position max and return the number now at position max. Decrement max by 1 and continue. When max is 0, set max back to the size of the array - 1 and start again without the need to reinitialize the array.


2 Answers

You may be interested in a linear feedback shift register. We used to build these out of hardware, but I've also done them in software. It uses a shift register with some of the bits xor'ed and fed back to the input, and if you pick just the right "taps" you can get a sequence that's as long as the register size. That is, a 16-bit lfsr can produce a sequence 65535 long with no repeats. It's statistically random but of course eminently repeatable. Also, if it's done wrong, you can get some embarrassingly short sequences. If you look up the lfsr, you will find examples of how to construct them properly (which is to say, "maximal length").

like image 178
gbarry Avatar answered Oct 02 '22 15:10

gbarry


A shuffle is a perfectly good way to do this (provided you do not introduce a bias using the naive algorithm). See Fisher-Yates shuffle.

like image 20
Mitch Wheat Avatar answered Oct 02 '22 17:10

Mitch Wheat