Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random sequence iteration in O(1) memory?

Say you want to iterate over a sequence [0 to n] in a random order, visiting every element exactly once. Is there any way to do this in O(1) memory, i.e. without creating an [1..n] sequence with std::iota and running it through std::random_shuffle?

Some kind of iterator spitting out the sequence in a random order would be optimal.

A requirement is that it should be possible to get another random order by picking another seed.

like image 905
4ZM Avatar asked Sep 17 '12 13:09

4ZM


1 Answers

If you could mutate the sequence in-place, you could simply repeatedly draw a random number from 0-N, and then erase the element you visited, or swap it to the end, or such schemes.

like image 186
Puppy Avatar answered Nov 15 '22 15:11

Puppy