Skip to content

Instantly share code, notes, and snippets.

@gene-ressler
Last active October 19, 2022 15:37
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 gene-ressler/c0cb09247d2c2e38f57bdd39679a757f to your computer and use it in GitHub Desktop.
Save gene-ressler/c0cb09247d2c2e38f57bdd39679a757f to your computer and use it in GitHub Desktop.
Permutation numbering
# For any 0 <= k < fact(n), return a unique permutation of [0..n-1].
# Functional inverse of number_from_perm().
def perm_from_number(n, k):
a = list(range(n))
p = []
for d in range(2, n + 1):
p.append(k % d)
k //= d
t = n - 1
for i in reversed(p):
a[t], a[i], t = a[i], a[t], t - 1
return a
# For any permutation of [0..n-1], return unique 0 <= k < fact(n).
# Functional inverse of perm_from_number().
def number_from_perm(p):
t = len(p) - 1
a = list(range(len(p)))
r = list(range(len(p)))
n = 0
for i in reversed(p[1:]):
n, a[r[i]], r[a[t]], t = t * (n + r[i]), a[t], r[i], t - 1
return n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment