Advent of Code 2022 - Day 2: Rock Paper Scissors Solution
Key-pair to the helpPart 1
Decrypt moves and calculate points
Implementation
1const fs = require("fs")23const data = fs4 .readFileSync("./input", "utf-8")5 .split(/\r?\n/)6 .filter(Boolean)7 .map(s => s.split(" "))89const OPPONENT_MOVE = { A: "R", B: "P", C: "S" }1011const PLAYER_MOVE = { X: "R", Y: "P", Z: "S" }1213const MOVE_POINT = { R: 1, P: 2, S: 3 }1415const 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}2122const res = data.reduce((acc, [encryptedOpponentMove, encryptedPlayerMove]) => {23 const [playerMove, opponentMove] = [24 PLAYER_MOVE[encryptedPlayerMove],25 OPPONENT_MOVE[encryptedOpponentMove],26 ]2728 return (29 acc + calculateOutcome(playerMove, opponentMove) + MOVE_POINT[playerMove]30 )31}, 0)3233console.log(res)
Part 2
Get player move from expected outcome and calculate the same way as Part 1
Implementation
1const fs = require("fs")23const data = fs4 .readFileSync("./input", "utf-8")5 .split(/\r?\n/)6 .filter(Boolean)7 .map(s => s.split(" "))89const OPPONENT_MOVE = { A: "R", B: "P", C: "S" }1011const MOVE_POINT = { R: 1, P: 2, S: 3 }1213const 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}1920const 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}2728const res = data.reduce((acc, [encryptedOpponentMove, needTo]) => {29 const [playerMove, opponentMove] = [30 getPlayerMoveIfNeedTo(needTo, OPPONENT_MOVE[encryptedOpponentMove]),31 OPPONENT_MOVE[encryptedOpponentMove],32 ]3334 return (35 acc + calculateOutcome(playerMove, opponentMove) + MOVE_POINT[playerMove]36 )37}, 0)3839console.log(res)
References
Comments
Loading comments...
Tags
adventofcode
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Advent of Code 2022 - Day 4: Camp Cleanup
Dealing with start, end
Previous Post
Advent of Code 2022 - Day 3: Rucksack Reorganization
Find shared item and calculate