Comment by brandonasuncion
Comment by brandonasuncion 8 days ago
Reminds me of a really cool coding trick to get a "random" permutation of an array in O(1) time/memory.
https://lemire.me/blog/2017/09/18/visiting-all-values-in-an-...
Comment by brandonasuncion 8 days ago
Reminds me of a really cool coding trick to get a "random" permutation of an array in O(1) time/memory.
https://lemire.me/blog/2017/09/18/visiting-all-values-in-an-...
I was reading into it and came across your blog post. It's a good followup read.
It has better avalanching compared to indexing by `(i * prime) % n`, but at the tradeoff of `n` being restricted to powers of 2.
I use "random" in quotation marks because it communicates the topic effectively and is very straight to the point. Colloquially, when people say "random" in the context of algorithms, it's generally understood to mean "pseudorandom" or "quasirandom". The trick is essentially an LCG using coprime numbers.
The blog post uses "random" in quotations as well in its title.
I call it O(1) because the ordering is fully determined just by choosing an arbitrary prime number. It's constant time to "reorder" the elements and also constant time to get the i'th element in the permutation. This is in contrast to something like the the Fisher-Yates shuffle which permutes the elements in O(n) time.
Feistel networks are another way to map your index from linear sequence to a pseudorandom permutation.