Day 2 is the game Rock Paper Scissors. We have an input file with a strategy guide:
A Y
B X
C Z
The first column is your opponent move and in the second how you should play. A is for Rock, B for Paper and C for Scissors. And the same X for Rock, Y for Paper and Z for Scissors. For me it is a bit confusing to reference those values in the code, so I remapped them during reading from input file:
moves = { "A" => "R", "B" => "P", "C" => "S", "X" => "R", "Y" => "P", "Z" => "S" }
data = File.
readlines("2.txt").
map(&:strip).
map { |item| item.split(" ") }.map do |(opponent, me)|
[moves[opponent], moves[me]]
end
What we need to do is calculate the final score. Here are the rules:
In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6).
moves = { "A" => "R", "B" => "P", "C" => "S", "X" => "R", "Y" => "P", "Z" => "S" }
data = File.
readlines("2.txt").
map(&:strip).
map { |item| item.split(" ") }.map do |(opponent, me)|
[moves[opponent], moves[me]]
end
map = {
"R" => 1,
"P" => 2,
"S" => 3
}
results = data.map do |(opponent, me)|
points = 0
if (opponent == "R" && me == "P") || (opponent == "P" && me == "S") || (opponent == "S" && me == "R")
points += 6
elsif opponent == me
points += 3
end
points += map[me]
points
end
puts results.sum
In Part B rules change to:
Now for the initial example you would get a total score of 12.
I am lazy so I just mapped all possible inputs, their respective scores and summed them up together:
moves = { "A" => "R", "B" => "P", "C" => "S", "X" => "R", "Y" => "P", "Z" => "S" }
strategy = {
# Rock
"AX" => 0 + 3,
"AY" => 3 + 1,
"AZ" => 6 + 2,
# Paper
"BX" => 0 + 1,
"BY" => 3 + 2,
"BZ" => 6 + 3,
# Scissors
"CX" => 0 + 2,
"CY" => 3 + 3,
"CZ" => 6 + 1
}
results = File.
readlines("2.txt").
map(&:strip).
map { |item| item.split(" ") }.map do |(opponent, me)|
strategy["#{opponent}#{me}"]
end
puts results.sum
Just to explain. For example "CZ" => 6 + 1
, opponent is playing Scissors and we need to win. We will get 6 points for the win and 1 point for playing Rock.