Day 12 partial
This commit is contained in:
80
2024/12/index.ts
Normal file
80
2024/12/index.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
const fs = require('fs');
|
||||
|
||||
const input = fs.readFileSync(__dirname + '/input.txt', 'utf8');
|
||||
|
||||
interface Coord { x: number, y: number };
|
||||
interface Plot { x: number, y: number, edges: number, corners: number };
|
||||
|
||||
const plots: Array<Array<string>> = input.split("\n").slice(0, -1).map((row: string) => row.split(''));
|
||||
|
||||
const height = plots.length;
|
||||
const width = plots[0].length;
|
||||
|
||||
const regions: Array<Array<Plot>> = [];
|
||||
|
||||
function getAllAdjacentPlots({ x, y }: Coord) {
|
||||
const letter = plots[y][x];
|
||||
plots[y][x] = '.'+letter;
|
||||
|
||||
const plot = { x, y, edges: 0, corners: 0 };
|
||||
|
||||
let adj: Array<Plot> = [plot];
|
||||
|
||||
let firstOneWasAnEdge = false;
|
||||
let lastOneWasAnEdge = false;
|
||||
[
|
||||
{ x, y: y - 1 },
|
||||
{ x: x + 1, y },
|
||||
{ x, y: y + 1 },
|
||||
{ x: x - 1, y },
|
||||
].forEach((adjCoord, i) => {
|
||||
const adjLetter = plots[adjCoord.y]
|
||||
&& plots[adjCoord.y][adjCoord.x]
|
||||
&& plots[adjCoord.y][adjCoord.x];
|
||||
if (adjLetter === letter) {
|
||||
adj = [...adj, ...getAllAdjacentPlots(adjCoord)];
|
||||
lastOneWasAnEdge = false;
|
||||
} else if (adjLetter !== '.'+letter) {
|
||||
plot.edges++;
|
||||
if (lastOneWasAnEdge) {
|
||||
plot.corners++;
|
||||
}
|
||||
lastOneWasAnEdge = true;
|
||||
}
|
||||
if (i === 0) {
|
||||
firstOneWasAnEdge = lastOneWasAnEdge;
|
||||
}
|
||||
});
|
||||
if (firstOneWasAnEdge && lastOneWasAnEdge) {
|
||||
plot.corners++;
|
||||
}
|
||||
return adj;
|
||||
}
|
||||
|
||||
for (let y = 0; y < plots.length; y++) {
|
||||
const row = plots[y];
|
||||
for (let x = 0; x < row.length; x++) {
|
||||
const char = row[x];
|
||||
if (char.startsWith('.')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
regions.push(getAllAdjacentPlots({ x, y }));
|
||||
}
|
||||
}
|
||||
|
||||
console.log(regions);
|
||||
let sum = 0;
|
||||
|
||||
regions.forEach((plots) => {
|
||||
const perim = plots.reduce((carry, { edges }) => carry + edges, 0);
|
||||
const vertices = plots.reduce((carry, { corners }) => carry + corners, 0);
|
||||
const area = plots.length;
|
||||
// Part 1
|
||||
// sum += perim * area;
|
||||
// Part 2
|
||||
sum += vertices * area;
|
||||
});
|
||||
|
||||
console.log(sum);
|
||||
|
||||
Reference in New Issue
Block a user