Skip to content

Commit

Permalink
2024D12: Part 1 wip
Browse files Browse the repository at this point in the history
  • Loading branch information
martapanc committed Dec 12, 2024
1 parent 617c94a commit e1745ac
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 0 deletions.
15 changes: 15 additions & 0 deletions 2024/src/2024/day12/day12.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {part1, part2} from "./day12";

describe('2024 Day 12', () => {
test('Part 1', async () => {
expect(await part1('testInput1')).toEqual(772);
expect(await part1('testInput2')).toEqual(140);
expect(await part1('testInput2')).toEqual(1930);
expect(await part1('input')).toEqual(44444);
});

test('Part 2', async () => {
expect(await part2('testInput1')).toEqual(31);
expect(await part2('input')).toEqual(29379307);
});
});
38 changes: 38 additions & 0 deletions 2024/src/2024/day12/day12.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import path from "node:path";
import {readInputLineByLine} from "@utils/io";
import {Coord, getNeighborCoords, getNeighbors, Grid, readLinesToGrid} from "@utils/grid";
import * as module from "node:module";

export async function part1(inputFile: string) {
return await day12(inputFile, calcAreaAndPerimeter);
}

export async function part2(inputFile: string) {
return await day12(inputFile);
}

async function day12(inputFile: string, calcFn?: (grid: Grid) => number) {
const inputPath = path.join(__dirname, inputFile);
const lines = await readInputLineByLine(inputPath);

return calcFn?.(readLinesToGrid(lines));
}

function calcAreaAndPerimeter(grid: Grid) {
let sum = 0;
const perimeterMap: Map<string, number> = new Map();
const areaMap: Map<string, number> = new Map();

for (const [coord, cell] of grid) {
const neighbors = getNeighbors(Coord.deserialize(coord), grid);
const perimeter = 4 - neighbors.filter(n => n === cell).length;
perimeterMap.set(cell, (perimeterMap.get(cell) || 0) + perimeter);
areaMap.set(cell, (areaMap.get(cell) || 0) + 1);
}

for (let [key, value] of perimeterMap) {
sum += value * areaMap.get(key)!;
}

return sum;
}
5 changes: 5 additions & 0 deletions 2024/src/2024/day12/testInput1
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
OOOOO
OXOXO
OOOOO
OXOXO
OOOOO
4 changes: 4 additions & 0 deletions 2024/src/2024/day12/testInput2
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
AAAA
BBCD
BBCC
EEEC
10 changes: 10 additions & 0 deletions 2024/src/2024/day12/testInput3
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
RRRRIICCFF
RRRRIICCCF
VVRRRCCFFF
VVRCCCJFFF
VVVVCJJCFE
VVIVCCJJEE
VVIIICJJEE
MIIIIIJJEE
MIIISIJEEE
MMMISSJEEE

0 comments on commit e1745ac

Please sign in to comment.