Skip to content

Commit

Permalink
Day13b: Solved
Browse files Browse the repository at this point in the history
  • Loading branch information
julemand101 committed Dec 26, 2024
1 parent fe7ce1e commit aaa16bf
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 17 deletions.
32 changes: 15 additions & 17 deletions lib/day13.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ final prizeRegExp = RegExp(r'X=(\d+), Y=(\d+)');
const costAButton = 3;
const costBButton = 1;

int solveA(Iterable<String> input) {
int solveA(Iterable<String> input) => solve(input, partB: false);
int solveB(Iterable<String> input) => solve(input, partB: true);

int solve(Iterable<String> input, {required bool partB}) {
var sum = 0;

for (final chunk in input
Expand All @@ -28,25 +31,20 @@ int solveA(Iterable<String> input) {
.groups(const [1, 2]).map((s) => int.parse(s!))
];
final [px, py] = [
...prizeRegExp
.firstMatch(chunk[2])!
.groups(const [1, 2]).map((s) => int.parse(s!))
...prizeRegExp.firstMatch(chunk[2])!.groups(const [1, 2]).map(
(s) => int.parse(s!) + (partB ? 10_000_000_000_000 : 0))
];

var cost = 0;
for (var a = 1; a <= 100; a++) {
for (var b = 1; b <= 100; b++) {
if ((a * ax) + (b * bx) == px && (a * ay) + (b * by) == py) {
if (cost == 0) {
cost = (a * costAButton) + (b * costBButton);
} else {
cost = min(cost, (a * costAButton) + (b * costBButton));
}
}
}
}
final aButton = ((by * px) - (bx * py)) / ((ax * by) - (ay * bx));
final bButton = ((ax * py) - (ay * px)) / ((ax * by) - (ay * bx));

sum += cost;
if (aButton > 0 &&
bButton > 0 &&
(aButton % 1) == 0 && // Checking if double values are whole
(bButton % 1) == 0 &&
(partB || (aButton <= 100 && bButton <= 100))) {
sum += (aButton.toInt() * costAButton) + (bButton.toInt() * costBButton);
}
}

return sum;
Expand Down
45 changes: 45 additions & 0 deletions test/day13_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,49 @@ Prize: X=18641, Y=10279
expect(solveA(input), equals(36571));
});
});
group('Part Two', () {
test('Example 1', () {
expect(
solveB(r'''
Button A: X+94, Y+34
Button B: X+22, Y+67
Prize: X=8400, Y=5400
'''
.asLines),
equals(0));
});
test('Example 2', () {
expect(
solveB(r'''
Button A: X+26, Y+66
Button B: X+67, Y+21
Prize: X=12748, Y=12176
'''
.asLines),
greaterThan(0));
});
test('Example 3', () {
expect(
solveB(r'''
Button A: X+17, Y+86
Button B: X+84, Y+37
Prize: X=7870, Y=6450
'''
.asLines),
equals(0));
});
test('Example 4', () {
expect(
solveB(r'''
Button A: X+69, Y+23
Button B: X+27, Y+71
Prize: X=18641, Y=10279
'''
.asLines),
greaterThan(0));
});
test('Solution', () {
expect(solveB(input), equals(85527711500010));
});
});
}

0 comments on commit aaa16bf

Please sign in to comment.