# A tiny quantum computer simulator in plain Python.
# The state of n qubits is a list of 2**n numbers called amplitudes, one for
# each result you could measure (00, 01, 10, 11 for two qubits).
# The chance of a result is its amplitude squared.
# Amplitudes can be complex numbers in general. These lessons only need real ones.

import math

S = 1 / math.sqrt(2)
H = [[S, S], [S, -S]]  # the Hadamard gate: makes an even mix of 0 and 1
X = [[0.0, 1.0], [1.0, 0.0]]  # the NOT gate: swaps 0 and 1


def RY(angle):
    # Turns the qubit by an angle. 0 leaves it at 0, pi turns it all the way to 1.
    c = math.cos(angle / 2)
    s = math.sin(angle / 2)
    return [[c, -s], [s, c]]


class Random:
    # Park-Miller random numbers, the same on every computer.
    def __init__(self, seed):
        self.state = seed

    def next(self):
        self.state = self.state * 16807 % 2147483647
        return self.state / 2147483647


def start(n):
    state = [0.0] * (2 ** n)
    state[0] = 1.0  # every qubit starts at 0
    return state


def apply(state, gate, qubit, n):
    bit = 1 << (n - 1 - qubit)  # qubit 0 is the left digit
    for i in range(len(state)):
        if i & bit == 0:
            a = state[i]
            b = state[i | bit]
            state[i] = gate[0][0] * a + gate[0][1] * b
            state[i | bit] = gate[1][0] * a + gate[1][1] * b


def cnot(state, control, target, n):
    # If the control qubit is 1, flip the target.
    c = 1 << (n - 1 - control)
    t = 1 << (n - 1 - target)
    for i in range(len(state)):
        if i & c and not i & t:
            state[i], state[i | t] = state[i | t], state[i]


def label(i, n):
    return format(i, "0" + str(n) + "b")


def show(state, n):
    for i in range(len(state)):
        a = state[i]
        p = a * a
        print(f"  |{label(i, n)}>  amplitude {a:6.3f}   chance {p:.3f}  " + "#" * int(p * 40 + 0.5))


def measure(state, shots, rng):
    counts = [0] * len(state)
    for _ in range(shots):
        r = rng.next()
        total = 0.0
        pick = len(state) - 1
        for i in range(len(state)):
            total += state[i] * state[i]
            if r < total:
                pick = i
                break
        counts[pick] += 1
    return counts
