from itertools import product

import numpy as np

from common import bit_oracle
from qsim import ONE, ZERO, apply, apply_cnot, kron


def logical_xor(x0, x1):
    return x0 ^ x1


U = bit_oracle(logical_xor, 2)
basis = [ZERO, ONE]

same = True
for x0, x1, y in product((0, 1), repeat=3):
    state = kron(basis[x0], basis[x1], basis[y])
    with_oracle = apply(state, U)
    # deux CNOT : contrôle x0 puis x1, cible y (qubit 2)
    with_cnots = apply_cnot(apply_cnot(state, 0, 2), 1, 2)
    same = same and np.allclose(with_oracle, with_cnots)
    out = int(np.argmax(np.abs(with_oracle)))
    print(f"|{x0}{x1}⟩|{y}⟩ → |{out:03b}⟩")
print("U_XOR = deux CNOT sur les 8 entrées :", same)
