Andrew Kensler's permute(), a stateless pseudorandom array iteration function
The post describes permute(), a function by Andrew Kensler that iterates over an array in pseudorandom[1] order and keeps no state between calls. It is used in graphics, especially offline rendering, and it can pick k unique items from an array of length n in random order, or draw a random sample without replacement. The author says the result is not cryptographically secure, but considers it good enough for computing rendering integrals and for casual statistical analysis.
The usual method is the Fisher-Yates shuffle[2], which needs O(n) time and memory. An incremental version that uses a sparse map reduces memory to O(k), but it still does not suit iterating over many arrays at once or sampling from very large data. permute() takes O(k) time and O(1) memory, and it can compute any random index in constant time, so it can run in parallel across threads or computers. Kensler described it in the paper Correlated Multi-Jittered Sampling. The author also cites a 2009 Stack Overflow answer with the same idea, so Kensler mainly popularized the method in graphics and created the particular hash function.
The function relies on an invertible hash function[3] for ranges whose size is a power of two, built from operations such as XOR and multiplication by an odd number. For arrays whose length is not a power of two, Kensler uses cycle-walking[4], a technique from cryptography. An update dated 27 May 2021 reports an improvement that extends the method to 64-bit integers.
Read the original andrew-helmer.github.ioDiscussion
Discussion
Commenters ask why Kensler's hash stays invertible when some bits are masked off. One reply explains that multiplication does not let high-order bits affect low-order bits, so multiplication by an odd number stays invertible even when only the lower bits are considered. Another comment describes the same property for XOR with a right-shifted copy of the index.
Sources
-
andrew-helmer.github.io
Andrew Kensler's permute(), a function for stateless, constant-time pseudorandom-order array iteration


