summaryrefslogtreecommitdiff
path: root/day-2/index.js
blob: 3671a9bca60e4431174777c1b9a6420cdc29ab43 (plain)
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
const fs = require('fs');
const input = fs.readFileSync('./day-2/input.txt').toString();

const lines = input.split('\n');

const [ROCK, PAPER, SCISSORS] = ['rock', 'paper', 'scissors'];
const [LOSS, WIN, DRAW] = ['loss', 'win', 'draw'];

const defeatMap = { // What defeats what
  [ROCK]: SCISSORS,
  [SCISSORS]: PAPER,
  [PAPER]: ROCK,
}

const shapeMap = {
  A: ROCK,
  B: PAPER,
  C: SCISSORS,

  X: ROCK,
  Y: PAPER,
  Z: SCISSORS,
}

const shapeScores = {
  [ROCK]: 1,
  [PAPER]: 2,
  [SCISSORS]: 3,
};

const outcomeScores = {
  [LOSS]: 0,
  [DRAW]: 3,
  [WIN]: 6
};

const result = lines.reduce((acc, line) => {
  const [opponentShape, shape] = line.split(' ').map(code => shapeMap[code]);
  if (!shape || !opponentShape) return acc;

  let outcome = LOSS;
  if (shape === opponentShape) outcome = DRAW;
  else if (defeatMap[shape] === opponentShape) outcome = WIN;

  return acc + shapeScores[shape] + outcomeScores[outcome];
}, 0)

console.log(result);