-
Notifications
You must be signed in to change notification settings - Fork 0
/
day2.js
91 lines (78 loc) · 1.82 KB
/
day2.js
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
84
85
86
87
88
89
90
91
import { parseLinesFromFile, writeAnswer } from './helpers.js';
const strategyMove1 = {
A: 'rock',
B: 'paper',
C: 'scissors',
};
const strategyMove2 = {
X: 'rock',
Y: 'paper',
Z: 'scissors',
};
const beats = {
rock: 'scissors',
paper: 'rock',
scissors: 'paper',
};
const losesTo = {
rock: 'paper',
paper: 'scissors',
scissors: 'rock',
};
const moveScore = {
X: 1,
Y: 2,
Z: 3,
rock: 1,
paper: 2,
scissors: 3,
}
const outcomeScore = {
X: 0,
Y: 3,
Z: 6,
}
function roundScore(player1, player2) {
const move1 = strategyMove1[player1];
const move2 = strategyMove2[player2];
if (move1 === move2) {
// draw
return 3;
}
if (beats[move2] === move1) {
// win
return 6
}
return 0;
}
function getMoveForOutcome(move, outcome) {
const played = strategyMove1[move];
if (outcome === 'Y') { // draw
return played;
}
if (outcome === 'Z') { // win
return losesTo[played];
}
// lose
return beats[played];
}
function solveProblem1(filename) {
const input = parseLinesFromFile(filename);
const totalScore = input.reduce((score, moves) => {
const [move1, move2] = moves.trim().split(' ');
return score + roundScore(move1, move2) + moveScore[move2];
}, 0);
writeAnswer(totalScore);
}
function solveProblem2(filename) {
const input = parseLinesFromFile(filename);
const totalScore = input.reduce((score, strategy) => {
const [move, outcome] = strategy.trim().split(' ');
const moveToPlay = getMoveForOutcome(move, outcome);
return score + moveScore[moveToPlay] + outcomeScore[outcome];
}, 0);
writeAnswer(totalScore, 2);
}
const filename = './day2.puzzle.txt';
solveProblem1(filename);
solveProblem2(filename);