This is something interesting I've found while attempting to shuffle $n$ values in a list is a deterministic way intended to look "random-ish". The idea is that you sort a number of values $r$ from $0...n-1$ into a list by starting with an index value $i=0$, then calculate the index for the new item to be inserted using the formula $i_1 = (i_0 + r)\mod n$. What I've found is that in most cases, there are several collisions where a number is placed over another except when $n = 2^k, k\in Z$.
I wrote a Python program to do this and display the output.
>>> for n in range(5,11):
print('_____')
num_list = ['' for i in range(n)]
i = 0
for r in range(n):
i = (i + r) % n
num_list[i] += str(r) + ','
for x in range(n):
print(str(x)+'|'+num_list[x])
_____
0|0,4,
1|1,3,
2|
3|2,
4|
_____
0|0,3,
1|1,
2|
3|2,5,
4|4,
5|
_____
0|0,6,
1|1,5,
2|
3|2,4,
4|
5|
6|3,
_____
0|0,
1|1,
2|4,
3|2,
4|7,
5|6,
6|3,
7|5,
_____
0|0,8,
1|1,4,7,
2|
3|2,6,
4|
5|
6|3,5,
7|
8|
_____
0|0,4,
1|1,6,
2|
3|2,
4|
5|5,9,
6|3,8,
7|
8|7,
9|
>>>
As you can see, multiple numbers are assigned to the same value for all cases except where n is a power of 2. Can anyone explain this?
1 2 4 8 16 32 64 128 256 512 1024 2048
Note Coder.shuffle(n) is running this algorithm and returning the resulting list
– Oliver Apr 30 '19 at 17:02