Using Sat4j as a Java library
Embedding a SAT solver in Java code
public class Example {
public static void main(String[] args) {
ISolver solver = SolverFactory.newDefault();
solver.setTimeout(3600);
Reader reader = new DimacsReader(solver);
PrintWriter out = new PrintWriter(System.out,true);
try {
IProblem problem = reader.parseInstance(args[0]);
if (problem.isSatisfiable()) {
System.out.println("Satisfiable !");
reader.decode(problem.model(),out);
} else {
System.out.println("Unsatisfiable !");
}
} catch (FileNotFoundException e) {
} catch (ParseFormatException e) {
} catch (IOException e) {
} catch (ContradictionException e) {
System.out.println("Unsatisfiable (trivial)!");
} catch (TimeoutException e) {
System.out.println("Timeout, sorry!");
}
}
}
Feeding a SAT solver without aReader
final int MAXVAR = 1000000;
final int NBCLAUSES = 500000;
ISolver solver = SolverFactory.newDefault();
solver.newVar(MAXVAR);
solver.setExpectedNumberOfClauses(NBCLAUSES);
for (int i=0;<NBCLAUSES;i++) {
int [] clause =
solver.addClause(new VecInt(clause));
}
IProblem problem = solver;
if (problem.isSatisfiable()) {
....
} else {
...
}
Iterating over all the models
ISolver solver = SolverFactory.newDefault();
ModelIterator mi = new ModelIterator(solver);
solver.setTimeout(3600);
Reader reader = new InstanceReader(mi);
try {
boolean unsat = true;
IProblem problem = reader.parseInstance(args[0]);
while (problem.isSatisfiable()) {
unsat = false;
int [] model = problem.model();
}
if (unsat)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParseFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ContradictionException e) {
System.out.println("Unsatisfiable (trivial)!");
} catch (TimeoutException e) {
System.out.println("Timeout, sorry!");
}