Skip to content

Instantly share code, notes, and snippets.

@DominikPeters
Created April 29, 2020 01:19
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 DominikPeters/211aa0eb89599189c6d18286142ec15e to your computer and use it in GitHub Desktop.
Save DominikPeters/211aa0eb89599189c6d18286142ec15e to your computer and use it in GitHub Desktop.
Compute Cayley distance between two rankings
# for two permutations of [0,1,...,n], compute how many swaps (not necessarily adjacent)
# are needed to transform one into the other
# code uses: distance of a permutation from the identity permutation
# equals n - #cycles in the cycle notation of the permutation
def cayley_distance(x,y):
A = range(len(x))
inv_y = tuple(y.index(a) for a in A)
comp = tuple(x[inv_y[a]] for a in A)
cycles = 0
rem = set(A)
while rem:
a = rem.pop()
cycles += 1
while comp[a] in rem:
a = comp[a]
rem.remove(a)
return len(A) - cycles
assert cayley_distance([0,1,2,3],[1,0,2,3]) == 1
assert cayley_distance([0,1,2,3],[1,0,3,2]) == 2
assert cayley_distance([2,1,3,0],[0,3,1,2]) == 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment