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 package org.sat4j.tools.encoding;
32
33 import org.sat4j.core.ConstrGroup;
34 import org.sat4j.core.VecInt;
35 import org.sat4j.specs.ContradictionException;
36 import org.sat4j.specs.IConstr;
37 import org.sat4j.specs.ISolver;
38 import org.sat4j.specs.IVecInt;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 public class Binomial extends EncodingStrategyAdapter {
54
55 @Override
56 public IConstr addAtMost(ISolver solver, IVecInt literals, int degree)
57 throws ContradictionException {
58 ConstrGroup group = new ConstrGroup();
59
60 IVecInt clause = new VecInt();
61
62 if (degree == 1) {
63 return addAtMostOne(solver, literals);
64 }
65
66 for (IVecInt vec : literals.subset(degree + 1)) {
67 for (int i = 0; i < vec.size(); i++) {
68 clause.push(-vec.get(i));
69 }
70 group.add(solver.addClause(clause));
71 clause.clear();
72 }
73 return group;
74
75 }
76
77 @Override
78 public IConstr addAtMostOne(ISolver solver, IVecInt literals)
79 throws ContradictionException {
80 ConstrGroup group = new ConstrGroup();
81
82 IVecInt clause = new VecInt();
83
84 for (int i = 0; i < literals.size() - 1; i++) {
85 for (int j = i + 1; j < literals.size(); j++) {
86 clause.push(-literals.get(i));
87 clause.push(-literals.get(j));
88 group.add(solver.addClause(clause));
89 clause.clear();
90 }
91 }
92 return group;
93 }
94
95 @Override
96 public IConstr addExactlyOne(ISolver solver, IVecInt literals)
97 throws ContradictionException {
98 ConstrGroup group = new ConstrGroup();
99
100 group.add(addAtLeastOne(solver, literals));
101 group.add(addAtMostOne(solver, literals));
102
103 return group;
104 }
105
106 @Override
107 public IConstr addExactly(ISolver solver, IVecInt literals, int degree)
108 throws ContradictionException {
109 ConstrGroup group = new ConstrGroup();
110
111 group.add(addAtLeast(solver, literals, degree));
112 group.add(addAtMost(solver, literals, degree));
113
114 return group;
115 }
116
117 @Override
118 public IConstr addAtLeast(ISolver solver, IVecInt literals, int degree)
119 throws ContradictionException {
120 if (degree == 1) {
121 return addAtLeastOne(solver, literals);
122 }
123
124 IVecInt negLiterals = new VecInt();
125
126 for (int i = 0; i < literals.size(); i++) {
127 negLiterals.push(-literals.get(i));
128 }
129
130 return addAtMost(solver, negLiterals, literals.size() - degree);
131 }
132
133 @Override
134 public IConstr addAtLeastOne(ISolver solver, IVecInt literals)
135 throws ContradictionException {
136 ConstrGroup group = new ConstrGroup();
137 IVecInt clause = new VecInt();
138
139 for (int i = 0; i < literals.size(); i++) {
140 clause.push(literals.get(i));
141 }
142 group.add(solver.addClause(clause));
143
144 return group;
145 }
146 }