diff --git a/lib/day13.dart b/lib/day13.dart index 02ba16b..8cc44a6 100644 --- a/lib/day13.dart +++ b/lib/day13.dart @@ -11,7 +11,10 @@ final prizeRegExp = RegExp(r'X=(\d+), Y=(\d+)'); const costAButton = 3; const costBButton = 1; -int solveA(Iterable input) { +int solveA(Iterable input) => solve(input, partB: false); +int solveB(Iterable input) => solve(input, partB: true); + +int solve(Iterable input, {required bool partB}) { var sum = 0; for (final chunk in input @@ -28,25 +31,20 @@ int solveA(Iterable 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; diff --git a/test/day13_test.dart b/test/day13_test.dart index edd46aa..e96529c 100644 --- a/test/day13_test.dart +++ b/test/day13_test.dart @@ -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)); + }); + }); }