|
| 1 | +import static com.github.pareronia.aoc.IntegerSequence.Range.range; |
1 | 2 | import static com.github.pareronia.aoc.Utils.toAString; |
2 | 3 | import static com.github.pareronia.aoc.itertools.IterTools.combinations; |
3 | 4 |
|
|
9 | 10 | import com.github.pareronia.aoc.solution.Samples; |
10 | 11 | import com.github.pareronia.aoc.solution.SolutionBase; |
11 | 12 |
|
| 13 | +import org.ojalgo.optimisation.Expression; |
| 14 | +import org.ojalgo.optimisation.ExpressionsBasedModel; |
| 15 | +import org.ojalgo.optimisation.Optimisation.Result; |
| 16 | +import org.ojalgo.optimisation.Variable; |
| 17 | + |
12 | 18 | import java.util.ArrayList; |
13 | 19 | import java.util.Arrays; |
14 | 20 | import java.util.List; |
@@ -50,13 +56,49 @@ public Long solvePart1(final List<Machine> machines) { |
50 | 56 | } |
51 | 57 |
|
52 | 58 | @Override |
| 59 | + @SuppressWarnings({ |
| 60 | + "PMD.AssignmentInOperand", |
| 61 | + "PMD.AvoidInstantiatingObjectsInLoops", |
| 62 | + "PMD.AvoidLiteralsInIfCondition" |
| 63 | + }) |
53 | 64 | public Long solvePart2(final List<Machine> machines) { |
54 | | - return 0L; |
| 65 | + long ans = 0L; |
| 66 | + for (final Machine machine : machines) { |
| 67 | + final int vars = machine.presses().size(); |
| 68 | + final int targets = machine.joltages().length; |
| 69 | + final double[][] a = new double[targets][vars]; |
| 70 | + range(vars).stream() |
| 71 | + .forEach( |
| 72 | + c -> Arrays.stream(machine.presses().get(c)).forEach(p -> a[p][c] = 1)); |
| 73 | + final ExpressionsBasedModel model = new ExpressionsBasedModel(); |
| 74 | + final List<Variable> variables = |
| 75 | + range(vars).stream() |
| 76 | + .map(c -> model.newVariable("x" + c).lower(0).integer().weight(1)) |
| 77 | + .toList(); |
| 78 | + range(targets).stream() |
| 79 | + .forEach( |
| 80 | + r -> { |
| 81 | + final Expression constraint = |
| 82 | + model.newExpression("c" + r).level(machine.joltages()[r]); |
| 83 | + for (int c = 0; c < vars; c++) { |
| 84 | + if (a[r][c] != 0d) { |
| 85 | + constraint.set(variables.get(c), a[r][c]); |
| 86 | + } |
| 87 | + } |
| 88 | + }); |
| 89 | + final Result result = model.minimise(); |
| 90 | + ans += |
| 91 | + range(vars) |
| 92 | + .intStream() |
| 93 | + .mapToLong(c -> Math.round(result.get(c).doubleValue())) |
| 94 | + .sum(); |
| 95 | + } |
| 96 | + return ans; |
55 | 97 | } |
56 | 98 |
|
57 | 99 | @Samples({ |
58 | 100 | @Sample(method = "part1", input = TEST, expected = "7"), |
59 | | - @Sample(method = "part2", input = TEST, expected = "0"), |
| 101 | + @Sample(method = "part2", input = TEST, expected = "33"), |
60 | 102 | }) |
61 | 103 | public static void main(final String[] args) throws Exception { |
62 | 104 | create().run(); |
|
0 commit comments