3 ms·
There's a similar trick that you can use to store permutations, where you use a variable base representation. For example, suppose that you need to store a per
by thequux 3y ago
There's a similar trick that you can use to store permutations, where you use a variable base representation.
For example, suppose that you need to store a permutation of 4 digits, [1,3,0,2]. The rightmost digit is base 4 and simply stores 1 directly. The second digit is base 3, but scale 4, and stores the position of 3 in [0,2,3] (because 1 has been removed from the set), i.e., 2. The third digit is 0 (base 2 scale 12) by similar reasoning, and the "fourth digit" would be base 1, which is always 0. Multiplying it out, you get 012 + 24 + 1 = 9.
Decoding follows a similar process:
9 % 4 = 1 9 / 4 = 2 [0,1,2,3][1] = 1
2 % 3 = 2 2 / 3 = 0 [0,2,3][2] = 3
0 % 2 = 0 0 / 2 = 0 [0,2][0] = 0
[2][0] = 2
The particularly observant reader will notice that the decoding algorithm is simply a deterministic Fisher-Yates shuffle, and the common optimization where you swap items from the source list instead of shifting them applies here as well.
This technique allows you to store permutations of up to 12 items in 32 bits, or 20 items in 64.