Skip to content

Instantly share code, notes, and snippets.

@austinjp
Last active April 1, 2023 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save austinjp/55a22701c40baa5bea0b372700881858 to your computer and use it in GitHub Desktop.
Save austinjp/55a22701c40baa5bea0b372700881858 to your computer and use it in GitHub Desktop.
A silly deterministic shuffle.

Just a note-to-self to prevent me from reinventing the wheel again.

A shuffle that always produces a predictable output.

e.g.

>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> dshuffle(x)
[7, 8, 1, 5, 3, 4, 2, 0, 9, 6]

>>> dshuffle(x)
[7, 8, 1, 5, 3, 4, 2, 0, 9, 6]

>>> dshuffle(x)
[7, 8, 1, 5, 3, 4, 2, 0, 9, 6]

Update the state to get new predictable values:

>>> rnd = Random(1) # different seed
>>> rnd_state = rnd.getstate()
>>> x = [0,1,2,3,4,5,6,7,8,9]
>>> dshuffle(x)
[6, 8, 9, 7, 5, 3, 0, 4, 1, 2]

>>> dshuffle(x)
[6, 8, 9, 7, 5, 3, 0, 4, 1, 2]

>>> dshuffle(x)
[6, 8, 9, 7, 5, 3, 0, 4, 1, 2]
from random import Random
rnd = Random(0)
rnd_state = rnd.getstate()
def dshuffle(i, sort=True):
rnd.setstate(rnd_state)
t = type(i)
x = list(i)
if sort:
try:
x = sorted(x)
except:
x = sorted(x, key=str)
rnd.shuffle(x)
if t == str:
return "".join(str(_) for _ in x)
try:
return type(t.__name__, (t,), {})(x)
except:
if t.__name__ == "generator":
return iter(x)
else:
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment