Files
advent-of-code-2022/2021/02/solution.ts
2022-12-05 21:47:28 +01:00

58 lines
1.7 KiB
TypeScript

const sample = await Deno.readTextFile("sample.txt");
const input = await Deno.readTextFile("input.txt");
const solvePart1 = (data: string): number =>
data
.split("\n")
.filter(Boolean)
.map((line) => line.split(" "))
.map(([action, amount]): [string, number] => [
action,
parseInt(amount) || 0,
])
.reduce(
([h, d], [action, amount]): [number, number] => {
if (action === "forward") {
return [h + amount, d];
} else if (action === "down") {
return [h, d + amount];
} else if (action === "up") {
return [h, d - amount];
}
throw new Error(`Unknown action ${action}`);
},
[0, 0] as [number, number]
)
.reduce((total, value) => total * value, 1);
console.log("Sample:", solvePart1(sample));
console.log("Input", solvePart1(input));
const solvePart2 = (data: string): number =>
data
.split("\n")
.filter(Boolean)
.map((line) => line.split(" "))
.map(([action, amount]): [string, number] => [
action,
parseInt(amount) || 0,
])
.reduce(
([h, d, a], [action, amount]): [number, number, number] => {
if (action === "forward") {
return [h + amount, d + amount * a, a];
} else if (action === "down") {
return [h, d, a + amount];
} else if (action === "up") {
return [h, d, a - amount];
}
throw new Error(`Unknown action ${action}`);
},
[0, 0, 0] as [number, number, number]
)
.filter((_, index) => index < 2)
.reduce((total, value) => total * value, 1);
console.log("Sample:", solvePart2(sample));
console.log("Input", solvePart2(input));