Skip to content

Commit

Permalink
Add AoC 2024 day 12 part 1 solver
Browse files Browse the repository at this point in the history
  • Loading branch information
h3x4d3c1m4l committed Dec 13, 2024
1 parent c99747d commit 91196f1
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
10 changes: 10 additions & 0 deletions assets/advent_of_code/2024_12_sample.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
RRRRIICCFF
RRRRIICCCF
VVRRRCCFFF
VVRCCCJFFF
VVVVCJJCFE
VVIVCCJJEE
VVIIICJJEE
MIIIIIJJEE
MIIISIJEEE
MMMISSJEEE
1 change: 1 addition & 0 deletions lib/solvers/advent_of_code/2024/_all_solvers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export 'day_04_solver.dart';
export 'day_05_solver.dart';
export 'day_06_solver.dart';
export 'day_11_solver.dart';
export 'day_12_solver.dart';
50 changes: 50 additions & 0 deletions lib/solvers/advent_of_code/2024/day_12_solver.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import 'package:h3x_devtools/solvers/advent_of_code/2024/aoc_2024_solver.dart';

class Day12Solver extends AdventOfCode2024Solver {

@override
final int dayNumber = 12;

@override
String getSolution(String input) {
Grid<String> grid = Grid.fromString(input, (value) => value);

// Part 1
Map<String, int> areaSizes = {}, perimeterLengths = {};
int currentAreaNameChar = 97;
for (int x = 0; x < grid.width; x++) {
for (int y = 0; y < grid.height; y++) {
Coordinates coordinates = Coordinates(x, y, grid);
Cell<String> cell = grid[coordinates];

// Area size
if (!areaSizes.containsKey(cell.obj)) {
// Because some area names can be used for multiple areas, make the area names unique.
grid.floodFill4Way(coordinates, cell.obj, String.fromCharCode(currentAreaNameChar));
currentAreaNameChar++;

areaSizes[cell.obj] = 1;
perimeterLengths[cell.obj] = 0;
} else {
areaSizes[cell.obj] = areaSizes[cell.obj]! + 1;
}

// Perimeter length
for (CardinalDirection direction in CardinalDirection.values) {
if (!coordinates.canGoCDirection(direction)) {
perimeterLengths[cell.obj] = perimeterLengths[cell.obj]! + 1;
} else {
Coordinates neighbor = coordinates.goToCDirection(direction);
if (grid[neighbor].obj != cell.obj) {
perimeterLengths[cell.obj] = perimeterLengths[cell.obj]! + 1;
}
}
}
}
}
int price1 = areaSizes.keys.map((key) => areaSizes[key]! * perimeterLengths[key]!).sum;

return 'Part 1 price: $price1';
}

}

0 comments on commit 91196f1

Please sign in to comment.