From c209f78d1a1f204a0772b45a49f0ee3cdb18ad83 Mon Sep 17 00:00:00 2001 From: Jacob Bang Date: Tue, 10 Dec 2024 07:08:23 +0100 Subject: [PATCH] Day10b: Solved --- lib/day10.dart | 33 ++++++++++++++++----------------- test/day10_test.dart | 12 ++++++------ 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/lib/day10.dart b/lib/day10.dart index a0e0621..f22fe58 100644 --- a/lib/day10.dart +++ b/lib/day10.dart @@ -4,32 +4,31 @@ import 'dart:collection'; import 'dart:typed_data'; -int solveA(List input) { - final grid = Grid(input.first.length + 2, input.length + 2) - ..setFromInput(input, padding: 1); - var sum = 0; +import 'package:collection/collection.dart'; - for (final startingPosition in grid.zeroPositions) { - sum += reachTop(grid, startingPosition, 0, HashSet()); - } +int solveA(List input) => solve(input, partB: false); +int solveB(List input) => solve(input, partB: true); - return sum; -} +int solve(List input, {required bool partB}) { + final grid = Grid(input.first.length + 2, input.length + 2) + ..setFromInput(input, padding: 1); -int solveB(List input) { - return 0; + return grid.zeroPositions + .map((startingPosition) => + reachTop(grid, startingPosition, 0, partB ? null : HashSet())) + .sum; } -final Point up = Point(0, -1); -final Point right = Point(1, 0); -final Point down = Point(0, 1); -final Point left = Point(-1, 0); +const Point up = Point(0, -1); +const Point right = Point(1, 0); +const Point down = Point(0, 1); +const Point left = Point(-1, 0); int reachTop( Grid grid, Point currentPosition, int nextLevel, - Set visitedBefore, + Set? visitedBefore, ) { final currentValue = grid.getByPoint(currentPosition); @@ -38,7 +37,7 @@ int reachTop( } if (currentValue == 9) { - return visitedBefore.add(currentPosition) ? 1 : 0; + return (visitedBefore?.add(currentPosition) ?? true) ? 1 : 0; } return reachTop(grid, currentPosition + up, nextLevel + 1, visitedBefore) + diff --git a/test/day10_test.dart b/test/day10_test.dart index f06c072..b8ac1a5 100644 --- a/test/day10_test.dart +++ b/test/day10_test.dart @@ -85,7 +85,7 @@ void main() { group('Part Two', () { test('Example 1', () { expect( - solveA(r''' + solveB(r''' .....0. ..4321. ..5..2. @@ -99,7 +99,7 @@ void main() { }); test('Example 2', () { expect( - solveA(r''' + solveB(r''' ..90..9 ...1.98 ...2..7 @@ -113,7 +113,7 @@ void main() { }); test('Example 3', () { expect( - solveA(r''' + solveB(r''' 012345 123456 234567 @@ -126,7 +126,7 @@ void main() { }); test('Example 4', () { expect( - solveA(r''' + solveB(r''' 89010123 78121874 87430965 @@ -140,7 +140,7 @@ void main() { equals(81)); }); test('Solution', () { - expect(solveB(input), equals(-1)); + expect(solveB(input), equals(1302)); }); - }, skip: true); + }); }