Created
December 8, 2017 21:44
-
-
Save nudded/ef3c29d38fa12c52a0a18076591e4fd3 to your computer and use it in GitHub Desktop.
day8.rb
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
input = File.readlines('inputs/day8.in') | |
REGISTERS = Hash.new {|h,k| h[k] = Register.new(k, 0,0)} | |
class Register < Struct.new(:name, :value, :highest_value); end | |
class Condition < Struct.new(:register, :condition, :value) | |
def check | |
case condition | |
when ">" | |
register.value > value | |
when "==" | |
register.value == value | |
when "<" | |
register.value < value | |
when "!=" | |
register.value != value | |
when ">=" | |
register.value >= value | |
when "<=" | |
register.value <= value | |
end | |
end | |
end | |
class Op < Struct.new(:amount, :condition) | |
def perform(register) | |
if condition.check | |
operation(register) | |
register.highest_value = [register.value, register.highest_value].max | |
end | |
end | |
end | |
class Increment < Op | |
def operation(register) | |
register.value += self.amount | |
end | |
end | |
class Decrement < Op | |
def operation(register) | |
register.value -= self.amount | |
end | |
end | |
input.each do |line| | |
line =~ /^(\w+) (inc|dec) (-?\d+) if (\w+) (.+) (-?\d+)$/ | |
condition = Condition.new(REGISTERS[$4], $5, $6.to_i) | |
operation_class = $2 == "inc" ? Increment : Decrement | |
operation = operation_class.new($3.to_i, condition) | |
operation.perform(REGISTERS[$1]) | |
end | |
puts "max value: #{REGISTERS.values.map(&:value).max}" | |
puts "max value during execution: #{REGISTERS.values.map(&:highest_value).max}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment