Skip to content

Instantly share code, notes, and snippets.

@bennacer860
Last active January 17, 2016 17:59
Show Gist options
  • Save bennacer860/4004f9029230a42f7c14 to your computer and use it in GitHub Desktop.
Save bennacer860/4004f9029230a42f7c14 to your computer and use it in GitHub Desktop.
require 'pry-byebug'
@wires = {}
def is_integer? n
return n.to_i.to_s == n
end
def first_pass
File.readlines('input.txt').each do |line|
line = line.split("->")
signal = line[0].strip
wire = line[1].strip
@wires[wire] = signal
end
end
def parse wire
# puts "enter wire #{wire}"
# binding.pry
wire = wire.strip
# we are dealing with an integer
return wire.to_i if is_integer? wire
# the gate has a value in our hash
return @wires[wire] if is_integer? @wires[wire]
# the gate has a signal
signal = @wires[wire]
tokens = signal.split(" ")
value = case tokens.count
when 3
operator = tokens[1]
left_operand = tokens[0]
right_operand = tokens[2]
case operator
when "AND"
parse(left_operand).to_i & parse(right_operand).to_i
when "OR"
parse(left_operand).to_i | parse(right_operand).to_i
when "LSHIFT"
parse(left_operand).to_i << parse(right_operand).to_i
when "RSHIFT"
parse(left_operand).to_i >> parse(right_operand).to_i
end
when 2
~ parse(tokens[1]).to_i
else
puts " store #{tokens[0]}"
# puts @wires
@wires[wire] = parse(tokens[0])
end
# puts "exit #{wire}"
value
end
first_pass
# p @wires
gate = 'a'
puts "#{gate} -> #{parse gate}"
# p @wires
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment