-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12a.js
60 lines (47 loc) · 1.3 KB
/
12a.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import {iterGrid, readInput} from "./lib.js";
const input = readInput(12).map(x => x.split(''));
const seenFence = new Set();
const seenArea = new Set();
let activePlant = null;
const areas = [];
iterGrid(input, (plant, x, y) => {
if (plant !== activePlant) {
activePlant = plant;
areas.push({
plant,
area: areaCount(x, y),
fence: areaFenceCount(x, y)
});
}
});
function areaCount(x, y) {
const plant = read(input, x, y, 0, 0);
if (plant !== activePlant) {
return 0;
}
if (seenArea.has(`${x},${y}`)) {
return 0;
}
seenArea.add(`${x},${y}`);
return 1 + areaCount(x + 1, y) + areaCount(x - 1, y) + areaCount(x, y + 1) + areaCount(x, y - 1);
}
function areaFenceCount(x, y) {
const plant = read(input, x, y, 0, 0);
if (plant !== activePlant) {
return 1;
}
if (seenFence.has(`${x},${y}`)) {
return 0;
}
seenFence.add(`${x},${y}`);
return areaFenceCount(x + 1, y) + areaFenceCount(x - 1, y) + areaFenceCount(x, y + 1) + areaFenceCount(x, y - 1);
}
function read(grid, x, y, dx, dy) {
return grid[y + dy]?.[x + dx];
}
console.log(
areas
.filter(({ fence}) => fence > 0)
.map(({ area, fence }) => area * fence)
.reduce((a, b) => a + b, 0)
);