-
Notifications
You must be signed in to change notification settings - Fork 5
/
day02.mjs
83 lines (73 loc) · 1.76 KB
/
day02.mjs
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
import { readFileSync } from "node:fs";
const lines = readFileSync("day02.txt", { encoding: "utf-8" }) // read day??.txt content
.replace(/\r/g, "") // remove all \r characters to avoid issues on Windows
.trim() // Remove starting/ending whitespace
.split("\n") // Split on newline
.map((line) => line.split(" ")); // Parse each line into a number
const moves = {
rock: 1,
paper: 2,
scissors: 3,
};
const mapInput = {
A: moves.rock,
B: moves.paper,
C: moves.scissors,
X: moves.rock,
Y: moves.paper,
Z: moves.scissors,
};
function score(opponentMove, ourMove) {
if (opponentMove === ourMove) {
return ourMove + 3;
}
if (
(opponentMove === moves.rock && ourMove === moves.paper) ||
(opponentMove === moves.paper && ourMove === moves.scissors) ||
(opponentMove === moves.scissors && ourMove === moves.rock)
) {
// We win
return ourMove + 6;
}
// We lost
return ourMove;
}
function part1() {
const outcomes = lines.map((line) => {
const opponentMove = mapInput[line[0]];
const ourMove = mapInput[line[1]];
return score(opponentMove, ourMove);
});
console.log(outcomes.reduce((a, b) => a + b, 0));
}
const solution = {
A: {
//rock
X: moves.scissors, //lose
Y: moves.rock, //draw
Z: moves.paper, //win
},
B: {
//paper
X: moves.rock,
Y: moves.paper,
Z: moves.scissors,
},
C: {
//scissors
X: moves.paper,
Y: moves.scissors,
Z: moves.rock,
},
};
function part2() {
const outcomes = lines.map((line) => {
const opponentMove = mapInput[line[0]];
// Guess our move from the instructions
const ourMove = solution[line[0]][line[1]];
return score(opponentMove, ourMove);
});
console.log(outcomes.reduce((a, b) => a + b, 0));
}
part1();
part2();