Created
December 14, 2021 10:03
-
-
Save alvinncx/2b7b37063cca572d0f1ea474356a01c7 to your computer and use it in GitHub Desktop.
Advent Of Code 2021 - Day 10 Solution (Part 2)
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
# Pretty simple challenge. The key is to loop through the string to keep finding instances of legal chucks and remove them. | |
# Chucks are made of itself so you can just keep removing the simplest chunks | |
class Line | |
attr_reader :temp | |
def initialize(raw) | |
@raw = raw | |
@temp = raw | |
parse | |
end | |
def corrupted? | |
@temp.include?(']') || @temp.include?(')') || @temp.include?('>') || @temp.include?('}') | |
end | |
def incomplete? | |
!corrupted? | |
end | |
def first_incorrect_closing_char | |
@temp.split('').each.with_index do |char, index| | |
next if char == '{' || char == '[' || char == '<' || char == '(' | |
return char | |
end | |
end | |
def score | |
case first_incorrect_closing_char | |
when ')' then 3 | |
when ']' then 57 | |
when '}' then 1197 | |
when '>' then 25137 | |
end | |
end | |
def closing_sequence | |
@mirrored = [] | |
@temp.split('').reverse_each do |char| | |
case char | |
when '(' then @mirrored.push(')') | |
when '[' then @mirrored.push(']') | |
when '{' then @mirrored.push('}') | |
when '<' then @mirrored.push('>') | |
end | |
end | |
@mirrored.join('') | |
end | |
def closing_sequence_score | |
score = 0 | |
@mirrored.each do |char| | |
score = score * 5 | |
case char | |
when ')' then score = score + 1 | |
when ']' then score = score + 2 | |
when '}' then score = score + 3 | |
when '>' then score = score + 4 | |
end | |
end | |
return score | |
end | |
private | |
def parse | |
while @temp.include?('[]') || @temp.include?('<>') || @temp.include?('()') || @temp.include?('{}') | |
@temp = @temp.split('[]').join('') | |
@temp = @temp.split('<>').join('') | |
@temp = @temp.split('()').join('') | |
@temp = @temp.split('{}').join('') | |
end | |
end | |
end | |
class Day10 | |
def self.run(input) | |
@lines = input.split("\n").map { |l| Line.new(l.strip) } | |
scores = @lines.select(&:incomplete?).each(&:closing_sequence).map(&:closing_sequence_score) | |
p scores.sort[scores.length / 2] | |
end | |
end | |
Day10.run('[({(<(())[]>[[{[]{<()<>> | |
[(()[<>])]({[<{<<[]>>( | |
{([(<{}[<>[]}>{[]{[(<()> | |
(((({<>}<{<{<>}{[]{[]{} | |
[[<[([]))<([[{}[[()]]] | |
[{[{({}]{}}([{[{{{}}([] | |
{<[[]]>}<{[{[{[]{()[[[] | |
[<(<(<(<{}))><([]([]() | |
<{([([[(<>()){}]>(<<{{ | |
<{([{{}}[<[[[<>{}]]]>[]]') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment