import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram

secret_number = '101001'

# here work is happen like buttom to up
for position,value in enumerate(reversed(secret_number)):
    if value == '1':
        print(position, value)

circuit = QuantumCircuit(6+1, 6)

circuit.h([0,1,2,3,4,5])
circuit.x(6)
circuit.h(6)
circuit.barrier()
circuit.draw(output='mpl')

circuit.cx(5, 6)
circuit.cx(3, 6)
circuit.cx(0, 6)
circuit.barrier()
circuit.draw(output='mpl')

circuit.h([0,1,2,3,4,5])
circuit.draw(output='mpl')

circuit.barrier()
circuit.measure([i for i in range(5)],[i for i in range(5)])
circuit.barrier()
circuit.draw(output='mpl')

simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)

circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))

circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()

for position,value in enumerate(reversed(secret_number)):
    if value == '1':
        circuit.cx(position, len(secret_number))

circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()

circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()

circuit.draw(output='mpl')

simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)

def find_secret_number(secter_number):
    secret_number = str(secter_number)
    # Using Bernstein Vazirani Algorithm
    circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))

    circuit.h(range(len(secret_number)))
    circuit.x(len(secret_number))
    circuit.h(len(secret_number))
    circuit.barrier()

    for position,value in enumerate(reversed(secret_number)):
        if value == '1':
            circuit.cx(position, len(secret_number))

    circuit.barrier()
    circuit.h(range(len(secret_number)))
    circuit.barrier()

    circuit.measure(range(len(secret_number)), range(len(secret_number)))
    circuit.barrier()

    circuit.draw(output='mpl')
    
    simulator = Aer.get_backend('qasm_simulator')
    job = execute(circuit, backend=simulator, shots=1)
    result = job.result()
    counts = result.get_counts()
    print(counts)

secret_number = int(input("enter number(digits should be 0 or 1): "))
find_secret_number(secret_number)

