Advent of Code 2022 - Day 2: Rock Paper Scissors Solution

Key-pair to the help

Part 1

Decrypt moves and calculate points

Implementation

1const fs = require("fs")
2
3const data = fs
4 .readFileSync("./input", "utf-8")
5 .split(/\r?\n/)
6 .filter(Boolean)
7 .map(s => s.split(" "))
8
9const OPPONENT_MOVE = { A: "R", B: "P", C: "S" }
10
11const PLAYER_MOVE = { X: "R", Y: "P", Z: "S" }
12
13const MOVE_POINT = { R: 1, P: 2, S: 3 }
14
15const calculateOutcome = (playerMove, opponentMove) => {
16 if (playerMove === opponentMove) return 3
17 const concatenation = playerMove + opponentMove
18 const winningPairs = ["RS", "PR", "SP"]
19 return winningPairs.includes(concatenation) ? 6 : 0
20}
21
22const res = data.reduce((acc, [encryptedOpponentMove, encryptedPlayerMove]) => {
23 const [playerMove, opponentMove] = [
24 PLAYER_MOVE[encryptedPlayerMove],
25 OPPONENT_MOVE[encryptedOpponentMove],
26 ]
27
28 return (
29 acc + calculateOutcome(playerMove, opponentMove) + MOVE_POINT[playerMove]
30 )
31}, 0)
32
33console.log(res)

Part 2

Get player move from expected outcome and calculate the same way as Part 1

Implementation

1const fs = require("fs")
2
3const data = fs
4 .readFileSync("./input", "utf-8")
5 .split(/\r?\n/)
6 .filter(Boolean)
7 .map(s => s.split(" "))
8
9const OPPONENT_MOVE = { A: "R", B: "P", C: "S" }
10
11const MOVE_POINT = { R: 1, P: 2, S: 3 }
12
13const calculateOutcome = (playerMove, opponentMove) => {
14 if (playerMove === opponentMove) return 3
15 const concatenation = playerMove + opponentMove
16 const winningPairs = ["RS", "PR", "SP"]
17 return winningPairs.includes(concatenation) ? 6 : 0
18}
19
20const getPlayerMoveIfNeedTo = (needTo, opponentMove) => {
21 return {
22 X: move => ({ R: "S", P: "R", S: "P" }[move]),
23 Y: move => ({ R: "R", P: "P", S: "S" }[move]),
24 Z: move => ({ R: "P", P: "S", S: "R" }[move]),
25 }[needTo](opponentMove)
26}
27
28const res = data.reduce((acc, [encryptedOpponentMove, needTo]) => {
29 const [playerMove, opponentMove] = [
30 getPlayerMoveIfNeedTo(needTo, OPPONENT_MOVE[encryptedOpponentMove]),
31 OPPONENT_MOVE[encryptedOpponentMove],
32 ]
33
34 return (
35 acc + calculateOutcome(playerMove, opponentMove) + MOVE_POINT[playerMove]
36 )
37}, 0)
38
39console.log(res)

References

Original problem

Comments

Loading comments...

Tags

adventofcode

Next Post

Advent of Code 2022 - Day 1: Calorie Counting

Dec 3, 2022

Straight-forward data manipulation

Previous Post

Advent of Code 2022 - Day 3: Rucksack Reorganization

Dec 3, 2022

Find shared item and calculate

HoningJS

Search Posts