-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
147 lines (134 loc) · 2.67 KB
/
index.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import run from "aocrunner";
import {
string as S,
readonlyArray,
array as A,
function as F,
nonEmptyArray as NEA,
option as O,
number as N,
boolean,
monoid,
} from "fp-ts";
const parseInput = (rawInput: string) =>
F.pipe(
rawInput,
S.trim,
S.split("\n"),
readonlyArray.toArray,
A.map(F.flow(S.trim, S.split(""), readonlyArray.toArray, A.map(parseInt))),
);
const toTreesInLine =
(map: number[][]) =>
([x, y]: number[]): number[][] =>
[
F.pipe(
NEA.range(0, y),
A.dropRight(1),
A.reverse,
A.map((y1) => map[y1][x]),
),
F.pipe(
NEA.range(y, map.length - 1),
NEA.tail,
A.map((y1) => map[y1][x]),
),
F.pipe(
NEA.range(0, x),
A.dropRight(1),
A.reverse,
A.map((x1) => map[y][x1]),
),
F.pipe(
NEA.range(x, map[0].length - 1),
NEA.tail,
A.map((x1) => map[y][x1]),
),
];
const toIsBlockedFromView =
(map: number[][]) =>
([x, y]: number[]): boolean =>
F.pipe(
[x, y],
toTreesInLine(map),
A.map(A.findIndex((height) => height >= map[y][x])),
A.every(O.isSome),
);
const toLineOfSight =
(map: number[][]) =>
([x, y]: number[]): number[] =>
F.pipe(
[x, y],
toTreesInLine(map),
A.map((trees) =>
F.pipe(
trees,
A.findIndex((height) => height >= map[y][x]),
O.map((index) => index + 1),
O.getOrElse(() => trees.length),
),
),
);
const toCoordinateTuples = (map: any[][]): [number, number][] =>
F.pipe(
NEA.range(0, map.length - 1),
NEA.map((y) =>
F.pipe(
NEA.range(0, map[0].length - 1),
A.map((x): [number, number] => [x, y]),
),
),
A.flatten,
);
const part1 = (rawInput: string) => {
const map = parseInput(rawInput);
const visibleTrees = F.pipe(
map,
toCoordinateTuples,
A.filter(F.flow(toIsBlockedFromView(map), boolean.BooleanAlgebra.not)),
A.size,
);
return visibleTrees;
};
const part2 = (rawInput: string) => {
const map = parseInput(rawInput);
const bestViewScore = F.pipe(
map,
toCoordinateTuples,
A.map(F.flow(toLineOfSight(map), monoid.concatAll(N.MonoidProduct))),
A.sort(N.Ord),
A.last,
O.getOrElse(() => 0),
);
return bestViewScore;
};
run({
part1: {
tests: [
{
input: `30373
25512
65332
33549
35390`,
expected: 21,
},
],
solution: part1,
},
part2: {
tests: [
{
input: `30373
25512
65332
33549
35390`,
expected: 8,
},
],
solution: part2,
},
trimTestInputs: true,
onlyTests: false,
});