"""Test: if [a,b] moves at most 4 points, is there z with z^-1 a z = a^-1 and z^-1 b z = b^-1 ?
Random pairs are produced from b^-1 a b = a c: pick a, pick c of small support with a*c conjugate to a,
then pick a random b conjugating a to a*c.  Control: the same with c a 5-cycle (expected to fail sometimes)."""
import random, sys
from collections import defaultdict

def mul(p, q):            # apply p then q  (permutations as tuples on 0..n-1)
    return tuple(q[p[i]] for i in range(len(p)))
def inv(p):
    r = [0] * len(p)
    for i, x in enumerate(p): r[x] = i
    return tuple(r)
def cycles(p):
    seen = [False] * len(p); out = []
    for i in range(len(p)):
        if not seen[i]:
            c = []; j = i
            while not seen[j]: seen[j] = True; c.append(j); j = p[j]
            out.append(c)
    return out
def ctype(p): return tuple(sorted(len(c) for c in cycles(p)))

def random_conjugator(a, d, rng):
    """random b with b^-1 a b = d  (i.e. a*b = b*d as 'apply left then right'), assuming same cycle type"""
    ca = defaultdict(list); cd = defaultdict(list)
    for c in cycles(a): ca[len(c)].append(c)
    for c in cycles(d): cd[len(c)].append(c)
    b = [0] * len(a)
    for L in ca:
        rng.shuffle(cd[L])
        for x, y in zip(ca[L], cd[L]):
            s = rng.randrange(L)
            for k in range(L): b[x[k]] = y[(k + s) % L]
    return tuple(b)

def simultaneous_conjugator(gens1, gens2):
    """z with z^-1 g z = h for each pair (g,h), or None.  Works orbit by orbit by propagating from one point."""
    n = len(gens1[0])
    def orbit_struct(gens, start):
        # canonical BFS labelling of the orbit of start
        order = [start]; idx = {start: 0}; table = []
        i = 0
        while i < len(order):
            row = []
            for g in gens + [inv(g) for g in gens]:
                y = g[order[i]]
                if y not in idx: idx[y] = len(order); order.append(y)
                row.append(idx[y])
            table.append(tuple(row)); i += 1
        return order, tuple(table)
    z = [None] * n; used = [False] * n
    done1 = [False] * n
    for s in range(n):
        if done1[s]: continue
        o1, t1 = orbit_struct(list(gens1), s)
        ok = False
        for t in range(n):
            if used[t]: continue
            o2, t2 = orbit_struct(list(gens2), t)
            if t1 == t2:
                for x, y in zip(o1, o2): z[x] = y; used[y] = True; done1[x] = True
                ok = True; break
        if not ok: return None
    return tuple(z)

def sample(n, kind, rng):
    while True:
        a = list(range(n)); rng.shuffle(a); a = tuple(a)
        pts = rng.sample(range(n), 5)
        c = list(range(n))
        if kind == '3':   c[pts[0]], c[pts[1]], c[pts[2]] = pts[1], pts[2], pts[0]
        elif kind == '22': c[pts[0]], c[pts[1]], c[pts[2]], c[pts[3]] = pts[1], pts[0], pts[3], pts[2]
        elif kind == '5':
            for k in range(5): c[pts[k]] = pts[(k + 1) % 5]
        d = mul(a, tuple(c))
        if ctype(d) == ctype(a):
            b = random_conjugator(a, d, rng)
            comm = mul(mul(inv(a), inv(b)), mul(a, b))
            assert comm == tuple(c)
            return a, b

rng = random.Random(11)
for kind in ('3', '22', '5'):
    for n in (6, 9, 12, 16, 24, 40):
        yes = no = 0
        for _ in range(400):
            a, b = sample(n, kind, rng)
            z = simultaneous_conjugator((a, b), (inv(a), inv(b)))
            if z is None: no += 1
            else:
                assert mul(mul(inv(z), a), z) == inv(a) and mul(mul(inv(z), b), z) == inv(b); yes += 1
        print(f'commutator type {kind:>2}, n={n:>2}: inverting z exists in {yes} of {yes+no}')
