Day 12 Part 2

This commit is contained in:
2024-12-12 23:06:11 +00:00
parent 2beaa0cdaa
commit ed25a377c7

View File

@@ -14,40 +14,52 @@ const regions: Array<Array<Plot>> = [];
function getAllAdjacentPlots({ x, y }: Coord) { function getAllAdjacentPlots({ x, y }: Coord) {
const letter = plots[y][x]; const letter = plots[y][x];
plots[y][x] = '.'+letter; plots[y][x] = '.' + letter;
const plot = { x, y, edges: 0, corners: 0 }; const plot = { x, y, edges: 0, corners: 0 };
let adj: Array<Plot> = [plot]; let adj: Array<Plot> = [plot];
let firstOneWasAnEdge = false; let adjLetters: Array<string> = [];
let lastOneWasAnEdge = false;
[ [
{ x, y: y - 1 }, { x, y: y - 1 },
{ x: x + 1, y: y - 1 },
{ x: x + 1, y }, { x: x + 1, y },
{ x: x + 1, y: y + 1 },
{ x, y: y + 1 }, { x, y: y + 1 },
{ x: x - 1, y: y + 1 },
{ x: x - 1, y }, { x: x - 1, y },
{ x: x - 1, y: y - 1 },
].forEach((adjCoord, i) => { ].forEach((adjCoord, i) => {
const adjLetter = plots[adjCoord.y] const adjLetter = plots[adjCoord.y]
&& plots[adjCoord.y][adjCoord.x]
&& plots[adjCoord.y][adjCoord.x]; && plots[adjCoord.y][adjCoord.x];
if (adjLetter === letter) {
adj = [...adj, ...getAllAdjacentPlots(adjCoord)]; if (i % 2 === 0) {
lastOneWasAnEdge = false; if (adjLetter === letter) {
} else if (adjLetter !== '.'+letter) { adj = [...adj, ...getAllAdjacentPlots(adjCoord)];
plot.edges++; } else if (adjLetter !== '.' + letter) {
if (lastOneWasAnEdge) { plot.edges++;
plot.corners++;
} }
lastOneWasAnEdge = true;
}
if (i === 0) {
firstOneWasAnEdge = lastOneWasAnEdge;
} }
adjLetters.push(adjLetter ? adjLetter.replace('.', '') : '_');
}); });
if (firstOneWasAnEdge && lastOneWasAnEdge) {
plot.corners++; for (let i = 1; i < 8; i += 2) {
let cornerLetter = adjLetters[i];
let beforeLetter = adjLetters[i - 1];
let afterLetter = adjLetters[i + 1] || adjLetters[0];
if (cornerLetter === letter && (beforeLetter === letter || afterLetter === letter)) {
continue;
}
if (
(beforeLetter === letter && afterLetter === letter)
|| (beforeLetter !== letter && afterLetter !== letter)
) {
plot.corners++;
}
} }
return adj; return adj;
} }
@@ -63,7 +75,6 @@ for (let y = 0; y < plots.length; y++) {
} }
} }
console.log(regions);
let sum = 0; let sum = 0;
regions.forEach((plots) => { regions.forEach((plots) => {
@@ -77,4 +88,3 @@ regions.forEach((plots) => {
}); });
console.log(sum); console.log(sum);