import pylab
import numpy as np
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua import run_algorithm
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle

input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''

oracle = LogicalExpressionOracle(input_3sat_instance)

grover = Grover(oracle)

backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])

plot_histogram(result['measurement'])

params = {
    'problem': {
        'name': 'search',
    },
    'algorithm': {
        'name': 'Grover'
    },
    'oracle': {
        'name': 'LogicalExpressionOracle',
        'expression': input_3sat_instance
    },
    'backend': {
        'shots': 1000,
    },
}

result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurement'])

expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
oracle = LogicalExpressionOracle(expression)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])

truthtable = '1000000000000001'

oracle = TruthTableOracle(truthtable)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])

#solution

from hide_toggle import hide_toggle
hide_toggle(for_next=True)

sat_cnf = '''
c  prova.cnf
c
p cnf 2 2
1 -2 0
-1 2 0
'''
#print(sat_cnf)
#oracle_2 = LogicalExpressionOracle(sat_cnf)
#my_grover = Grover(oracle_2)
#backend = BasicAer.get_backend('qasm_simulator')
#quantum_grover = QuantumInstance(backend, shots=1024)
#result = grover.run(quantum_grover)
#print(result['result'])

