r/dailyprogrammer • u/Steve132 0 1 • Aug 09 '12
[8/8/2012] Challenge #86 [difficult] (2-SAT)
Boolean Satisfiability problems are problems where we wish to find solutions to boolean equations such as
(x_1 or not x_3) and (x_2 or x_3) and (x_1 or not x_2) = trueThese problems are notoriously difficult, and k-SAT where k (the number of variables in an or expression) is 3 or higher is known to be NP-complete.
However, 2-SAT instances (like the problem above) are NOT NP-complete (if P!=NP), and even have linear time solutions.
You can encode an instance of 2-SAT as a list of pairs of integers by letting the integer represent which variable is in the expression, with a negative integer representing the negation of that variable. For example, the problem above could be represented in list of pair of ints form as
[(1,-3),(2,3),(1,-2)]Write a function that can take in an instance of 2-SAT encoded as a list of pairs of integers and return a boolean for whether or not there are any true solutions to the formula.
1
u/[deleted] Aug 09 '12
2-SAT isn't known to not be NP-complete.
10
u/Midwestbest8 Aug 09 '12
In J:
~.,!#%#{}#|+=
2
u/Ledrug 0 2 Aug 10 '12
Linear algorithm. Gives only a "yes" or "no" to 2-sat problem.
3
u/Tekmo Aug 09 '12
Haskell:
1
u/5outh 1 0 Aug 09 '12 edited Aug 09 '12
Here's a brute-force k-sat.
1
u/skeeto -9 8 Aug 09 '12 edited Aug 09 '12
Elisp / Common Lisp. This solves 2-SATs by brute-force. For the sake of brevity it doesn't use short-cutting, so it's not as efficient as it could be.
Usage:
1
u/stonegrizzly Aug 10 '12
python backtracking solution
output: