Skip to content

Instantly share code, notes, and snippets.

@s4lt3d
Created March 7, 2024 22:30
Show Gist options
  • Select an option

  • Save s4lt3d/9584cd317fc8ea02e0aa9f6e85598382 to your computer and use it in GitHub Desktop.

Select an option

Save s4lt3d/9584cd317fc8ea02e0aa9f6e85598382 to your computer and use it in GitHub Desktop.
# Random shuffle which accounts for non-repeating elements after looping shuffles
# Useful for games which do random actions but you never want to see the same action twice in a row
import random
def knuth_shuffle(a, prev_end):
for i in range(len(a)-1,1, -1):
j = random.randint(0, i)
a[i], a[j] = a[j], a[i]
if a[0] == prev_end:
j = random.randint(0, len(a)-1)
a[0], a[j] = a[j], a[0]
return a
a = [1, 2, 3]
for i in range(10):
a = knuth_shuffle(a, a[len(a)-1])
print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment