Created
December 2, 2022 17:16
-
-
Save twopoint718/e47f1b341e8d7afc643307552afaca4b to your computer and use it in GitHub Desktop.
Advent of Code 2022 (parts 1 & 2) using matrix multiplication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
require 'matrix' | |
class RPS | |
attr_accessor :scoring, :choices | |
def initialize | |
@scoring = Matrix[ | |
[1, 0, 2], | |
[2, 1, 0], | |
[0, 2, 1] | |
] | |
@choices = scoring.transpose.rotate_entries | |
end | |
def read_letter(letter) | |
case letter | |
when 'A', 'X' then 0 | |
when 'B', 'Y' then 1 | |
when 'C', 'Z' then 2 | |
else raise("Bad letter #{letter}") | |
end | |
end | |
def score(opponent, player) | |
o = read_letter(opponent) | |
p = read_letter(player) | |
(scoring * 3)[o, p] + (p + 1) | |
end | |
def score2(opponent, player) | |
o = read_letter(opponent) | |
p = read_letter(player) | |
choice = choices[o, p] | |
(scoring * 3)[o, choice] + (choice + 1) | |
end | |
end | |
rps = RPS.new | |
result = STDIN | |
.readlines | |
.map(&:split) | |
.map { |o, p| rps.score2(o, p) } | |
.sum | |
puts result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment