Skip to content

Instantly share code, notes, and snippets.

@alvinncx
Created December 14, 2021 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvinncx/2b7b37063cca572d0f1ea474356a01c7 to your computer and use it in GitHub Desktop.
Save alvinncx/2b7b37063cca572d0f1ea474356a01c7 to your computer and use it in GitHub Desktop.
Advent Of Code 2021 - Day 10 Solution (Part 2)
# 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