-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
74 lines (55 loc) · 1.62 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
import { RADIX } from '../../../utils/math.ts';
function permutater<T>(arr: T[]) {
const result: T[][] = [];
function permute(accumulator: T[], memo: T[] = []) {
if (!accumulator.length) {
result.push(memo);
} else {
for (let i = 0; i < accumulator.length; i += 1) {
const current = accumulator.slice();
const next = current.splice(i, 1);
permute(current.slice(), memo.concat(next));
}
}
}
permute(arr);
return result;
}
interface Route {
from: string;
to: string;
distance: number;
}
function parseRoute(route: string): Route {
const { groups } = route.match(/(?<from>\w+) to (?<to>\w+) = (?<distance>\d+)/);
const { from, to, distance } = groups;
return {
from,
to,
distance: parseInt(distance, RADIX),
};
}
function mapRoutes(routes: string[], distances: Map<string, number>): number {
let total = 0;
for (let i = 0; i < routes.length - 1; i += 1) {
const current = routes[i];
const next = routes[i + 1];
total += distances.get(`${current} -> ${next}`) || 0;
}
return total;
}
function part1(routes: string[]): number {
const distances = new Map<string, number>();
const places = new Set<string>();
routes.forEach((route) => {
const { from, to, distance } = parseRoute(route);
distances.set(`${from} -> ${to}`, distance);
distances.set(`${to} -> ${from}`, distance);
places.add(from);
places.add(to);
});
const allRoutes = permutater(Array.from(places));
const mappedRoutes = allRoutes.map((allRoute) => mapRoutes(allRoute, distances));
return Math.min(...mappedRoutes);
}
export { part1 };