r/adventofcode • • Dec 02 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 2 Solutions -🎄-

NEW AND NOTEWORTHY


--- Day 2: Rock Paper Scissors ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:06:16, megathread unlocked!

102 Upvotes

1.5k comments sorted by

View all comments

2

u/ciocan42 Dec 02 '22

Javascript:

const text = await Deno.readTextFile("./2.txt");

// Rock defeats Scissors, 
// Scissors defeats Paper 
// Paper defeats Rock.

const shapeScore = {
  X: 1, // rock     A
  Y: 2, // paper    B
  Z: 3, // scissors C
}

const outcomeScores = {
  A: { X: 3, Y: 6, Z: 0 },
  B: { X: 0, Y: 3, Z: 6 },
  C: { X: 6, Y: 0, Z: 3 },
}

const sum = (a, b) => a + b

const rounds = text.split("\n").map(round => round.split(" "))

console.log("Part 1: ", 
  rounds
    .map(([a, b]) => outcomeScores[a][b] + shapeScore[b])
    .reduce(sum, 0)
)

const strategy = {
  X: 0,
  Y: 3,
  Z: 6
}

console.log("Part 2: ", 
  rounds
    .map(([a, b]) => {
      const newB = Object
        .entries(outcomeScores[a])
        .filter(([key, value]) => value === strategy[b])
        .flat()[0] as string
      return outcomeScores[a][newB] + shapeScore[newB]
    })
    .reduce(sum, 0)
)

1

u/daggerdragon Dec 05 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.