Skip to content

Commit

Permalink
Day06b: Solved (slowly)
Browse files Browse the repository at this point in the history
  • Loading branch information
julemand101 committed Dec 7, 2024
1 parent 90250da commit eaa9cfc
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 8 deletions.
57 changes: 51 additions & 6 deletions lib/day06.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,56 @@ const movements = [
Point(-1, 0),
];

int solveA(List<String> input) {
int solveA(List<String> input) =>
getDistinctPositions(input).distinctPositions.length;

int solveB(List<String> input) {
final (:distinctPositions, :grid) = getDistinctPositions(input);

// Now contains places we can place obstacles
distinctPositions.remove(grid.guardStartingPoint);
var loopPositions = 0;

for (final distinctPosition in distinctPositions) {
// Put obstacle at position
grid.setByPoint(distinctPosition, obstructionChar);

// Point and direction set. If we detect the same combo, we are in loop
final loopDetect = <(Point, int)>{};
var guardPosition = grid.guardStartingPoint;
var direction = 0;

while (true) {
if (!loopDetect.add((guardPosition, direction))) {
loopPositions++;
break;
}

final nextGuardPosition = guardPosition + movements[direction];
final objectOnNewPosition = grid.getByPoint(nextGuardPosition);

if (objectOnNewPosition == null) {
// Hit outside of grid which means we are done
break;
} else if (objectOnNewPosition == obstructionChar) {
// Hit obstacle so rotate
direction = (direction + 1) % movements.length;
} else {
// Move to free space
guardPosition = nextGuardPosition;
}
}

// Reset grid back to original map
grid.setByPoint(distinctPosition, emptyChar);
}

return loopPositions;
}

({Set<Point> distinctPositions, Grid grid}) getDistinctPositions(
List<String> input,
) {
final grid = Grid(input.first.length, input.length)..setFromInput(input);
final distinctPositions = <Point>{};

Expand All @@ -43,11 +92,7 @@ int solveA(List<String> input) {
}
}

return distinctPositions.length;
}

int solveB(List<String> input) {
return 0;
return (distinctPositions: distinctPositions, grid: grid);
}

extension type const Point._(({int x, int y}) _point) {
Expand Down
4 changes: 2 additions & 2 deletions test/day06_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ void main() {
equals(6));
});
test('Solution', () {
expect(solveB(input), equals(-1));
expect(solveB(input), equals(1443));
});
}, skip: true);
});
}

0 comments on commit eaa9cfc

Please sign in to comment.