How to shuffle a function consistently from a seed number

79 Views Asked by At

I need a algorithm that sorts a list in a consistent way when given a input seed number and a list of unique items to shuffle. Here are the properties it must satisfy: Let's call the algorithm function(list, seed_value)

  • No randomness which means function([1, 2, 3, 4], n) is the same as function([1, 2, 3, 4], n) the next time it is called
  • Every seed number that is more than 0 and less than or equal to the number of permutations of the list possible must give a unique shuffled list from the others.
  • It is an algorithm, not a lookup table
  • Efficient, timewise and spacewise
  • As few loops as possible
  • Easy to understand if possible

It's... a bit hard for me to comprehend so I am asking you people to help. (btw even if it is not really random it doesn't matter for me)

1

There are 1 best solutions below

0
btilly On

Here is an implementation of n-th permutation.

def shuffle (values, n):
    for m in range(1, len(values)):
        i = n % (m+1)
        values[m], values[i] = values[i], values[m]
        n = n // (m+1)
    return values

for i in range(24):
    print(shuffle(['a', 'b', 'c', 'd'], i))

Here is why it works. When we arrive at the mth iteration of the loop, the values at indexes 0, 1, ..., m-1 have already been shuffled. We then swap the m'th index with any one of them based on the remainder of n / (m+1). And now the values at indexes 0, 1, ..., m have been shuffled. We divide n by m+1 to get rid of the information we used, and we arrive at the next loop.