Last active
October 19, 2022 15:37
-
-
Save gene-ressler/c0cb09247d2c2e38f57bdd39679a757f to your computer and use it in GitHub Desktop.
Permutation numbering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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