-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
79 lines (66 loc) · 1.91 KB
/
mod.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
import { data, sample } from "./data.ts";
import { Entry } from "./interfaces.ts";
const input = data.split("\n");
const timestamp = Number(input[0]);
const busIds = input[1].split(",").filter((s) => s !== "x").map((n) =>
Number(n)
);
function buildTimeTable(timestamp: number, busIds: number[]) {
const chart: Entry = {
...busIds.reduce((all, cur) => {
return {
...all,
[cur]: [],
};
}, {}),
};
let index = 0, bid = 0;
let lowest = timestamp * timestamp;
while (index < timestamp) {
for (const id of busIds) {
const product = id * index;
if (
product >= timestamp && chart[id].length === 0 && product % id === 0
) {
if (product - timestamp >= 0 && product - timestamp < lowest) {
lowest = product - timestamp;
bid = id;
}
chart[id].push(product);
}
}
index++;
}
return {
bid,
lowest,
chart,
};
}
function getEarliestTimestamp(busIds: string[]) {
let finalTime = BigInt(1);
let multiplier = BigInt(1);
const busIdOffsets = busIds
.map((id, offsetIndex) => ({
id: id === "x" ? BigInt(0) : BigInt(id),
offsetIndex: BigInt(offsetIndex),
}))
.filter((bt) => bt.id !== BigInt(0));
for (const bus of busIdOffsets) {
while ((bus.offsetIndex + finalTime) % bus.id !== BigInt(0)) {
finalTime += multiplier;
}
multiplier *= BigInt(bus.id);
}
return finalTime;
}
const table = buildTimeTable(timestamp, busIds);
const earilestTimestamp = getEarliestTimestamp(input[1].split(","));
console.log(
"[Part 1] What is the ID of the earliest bus you can take to the airport multiplied by the number of minutes you'll need to wait for that bus?",
table.bid * table.lowest,
);
console.log(
"[Part 2] What is the Manhattan distance between that location and the ship's starting position?",
Number((earilestTimestamp).toString().replace("n", "")),
);