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

Key-pair to the help

## Part 1

Decrypt moves and calculate points

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}const fs = require("fs")2
3const data = fs4  .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 317  const concatenation = playerMove + opponentMove18  const winningPairs = ["RS", "PR", "SP"]19  return winningPairs.includes(concatenation) ? 6 : 020}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 = fs4  .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 315  const concatenation = playerMove + opponentMove16  const winningPairs = ["RS", "PR", "SP"]17  return winningPairs.includes(concatenation) ? 6 : 018}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)```

Original problem

## 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

Search Posts