80 lines
2.0 KiB
TypeScript
80 lines
2.0 KiB
TypeScript
const sample = await Deno.readTextFile("sample.txt");
|
|
const input = await Deno.readTextFile("input.txt");
|
|
|
|
type Object = "rock" | "paper" | "scissor";
|
|
type Outcome = "LOST" | "DRAW" | "WIN";
|
|
|
|
const scores: Record<Outcome, number> = {
|
|
LOST: 0,
|
|
DRAW: 3,
|
|
WIN: 6,
|
|
} as const;
|
|
|
|
const objectValues: Record<Object, number> = {
|
|
rock: 1,
|
|
paper: 2,
|
|
scissor: 3,
|
|
} as const;
|
|
|
|
const objectsWinFrom: Record<Object, Object> = {
|
|
rock: "scissor",
|
|
paper: "rock",
|
|
scissor: "paper",
|
|
} as const;
|
|
|
|
const codesToObjects: Record<string, Object> = {
|
|
A: "rock",
|
|
B: "paper",
|
|
C: "scissor",
|
|
X: "rock",
|
|
Y: "paper",
|
|
Z: "scissor",
|
|
} as const;
|
|
|
|
const codesToOutcome: Record<string, Outcome> = {
|
|
X: "LOST",
|
|
Y: "DRAW",
|
|
Z: "WIN",
|
|
} as const;
|
|
|
|
const solvePart1 = (data: string): number | undefined =>
|
|
data
|
|
.split("\n")
|
|
.filter(Boolean)
|
|
.map((line) => line.split(" ").map((code) => codesToObjects[code]))
|
|
.map(([object1, object2]) => {
|
|
if (object2 === object1) {
|
|
return scores.DRAW + objectValues[object2];
|
|
}
|
|
if (objectsWinFrom[object2] === object1) {
|
|
return scores.WIN + objectValues[object2];
|
|
}
|
|
return scores.LOST + objectValues[object2];
|
|
})
|
|
.reduce((sum, value) => sum + value, 0);
|
|
|
|
console.log("Sample:", solvePart1(sample));
|
|
console.log("Input", solvePart1(input));
|
|
|
|
const solvePart2 = (data: string): number | undefined =>
|
|
data
|
|
.split("\n")
|
|
.filter(Boolean)
|
|
.map((line): [Object, Outcome] => {
|
|
const [objectCode, outcomeCode] = line.split(" ");
|
|
return [codesToObjects[objectCode], codesToOutcome[outcomeCode]];
|
|
})
|
|
.map(([object1, outcome]) => {
|
|
if (outcome === "DRAW") {
|
|
return scores.DRAW + objectValues[object1];
|
|
}
|
|
if (outcome === "LOST") {
|
|
return scores.LOST + objectValues[objectsWinFrom[object1]];
|
|
}
|
|
return scores.WIN + objectValues[objectsWinFrom[objectsWinFrom[object1]]];
|
|
})
|
|
.reduce((sum, value) => sum + value, 0);
|
|
|
|
console.log("Sample:", solvePart2(sample));
|
|
console.log("Input", solvePart2(input));
|