-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqiskit_grover_sudoku.py
84 lines (61 loc) · 1.99 KB
/
qiskit_grover_sudoku.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from qiskit import Aer, transpile
from qiskit.circuit import AncillaRegister, ClassicalRegister, Gate, QuantumCircuit, QuantumRegister
from qiskit.circuit.library import HGate, ZGate
def xor():
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[2])
qc.cx(qr[1], qr[2])
return qc
def check_rows_columns():
qr = QuantumRegister(4, 'in')
ar = AncillaRegister(4, 'tmp')
qc = QuantumCircuit(qr, ar)
qc.append(xor(), [qr[0], qr[1], ar[0]])
qc.append(xor(), [qr[2], qr[3], ar[1]])
qc.append(xor(), [qr[0], qr[2], ar[2]])
qc.append(xor(), [qr[1], qr[3], ar[3]])
return qc
def sudoku_oracle():
qr = QuantumRegister(4)
ar = AncillaRegister(4)
out = QuantumRegister(1)
qc = QuantumCircuit(qr, ar, out)
qc.append(check_rows_columns(), list(qr) + list(ar))
qc.mcx(ar, out)
qc.append(check_rows_columns().inverse(), list(qr) + list(ar))
return qc
def reflect_zero(nqubits: int):
qr = QuantumRegister(nqubits)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.append(ZGate().control(nqubits - 1), qr)
qc.x(qr)
return qc
def reflect_initial(init_gate: Gate, nqubits: int):
qr = QuantumRegister(nqubits)
qc = QuantumCircuit(qr)
qc.append(init_gate.inverse(), [qr])
qc.append(reflect_zero(nqubits), qr)
qc.append(init_gate, [qr])
return qc
def create_grover_circuit():
qr = QuantumRegister(4, 'in')
ar = AncillaRegister(4, 'anc')
pkb = QuantumRegister(1, 'pkb')
output = ClassicalRegister(4, 'out')
qc = QuantumCircuit(qr, ar, pkb, output)
qc.h(qr)
qc.x(pkb)
qc.h(pkb)
for i in range(2):
qc.append(sudoku_oracle(), list(qr) + list(ar) + list(pkb))
qc.append(reflect_initial(HGate(), 4), qr)
qc.measure(qr, output)
return qc
circuit = create_grover_circuit()
backend = Aer.get_backend('aer_simulator')
results = backend.run(transpile(circuit, backend), shots=512).result()
counts = results.get_counts()
print(counts["0110"])
print(counts["1001"])