AoC2015/day07/solution.rb

93 lines
2.7 KiB
Ruby

#!/bin/env ruby
require 'pry'
input = File.readlines('./input').map(&:strip)
input.map! { |line| line.split('->') }
wires = input.to_h { |pair| [pair[1].strip.to_sym, nil] }
input.cycle.with_index do |line, _i|
instruction = line.dup
instruction[1].strip!
instruction[0] = instruction[0].split(' ')
instruction[0].map! do |item|
if wires.has_key?(item.to_sym)
wires[item.to_sym]
elsif item =~ /AND|OR|NOT|LSHIFT|RSHIFT/
item
else
item.to_i
end
end
next if instruction[0].include?(nil)
if instruction[0].include?('AND')
wires[instruction[1].to_sym] = instruction[0][0] & instruction[0][2]
input.delete(instruction)
elsif instruction[0].include?('OR')
wires[instruction[1].to_sym] = instruction[0][0] | instruction[0][2]
input.delete(instruction)
elsif instruction[0].include?('NOT')
wires[instruction[1].to_sym] = instruction[0][1] ^ 65_535
input.delete(instruction)
elsif instruction[0].include?('LSHIFT')
wires[instruction[1].to_sym] = instruction[0][0] << instruction[0][2]
input.delete(instruction)
elsif instruction[0].include?('RSHIFT')
wires[instruction[1].to_sym] = instruction[0][0] >> instruction[0][2]
input.delete(instruction)
else
wires[instruction[1].to_sym] = instruction[0][0]
end
input.delete(line)
# break if i > 1000
end
puts "Part 1 Solution: #{wires[:a]}"
# Part 2, getting sloppy again :)
b = wires[:a]
wires.transform_values! { |_v| nil }
wires[:b] = b
pp wires[:b]
input = File.readlines('./input').map(&:strip)
input.map! { |line| line.split('->') }
input.cycle.with_index do |line, _i|
instruction = line.dup
instruction[1].strip!
instruction[0] = instruction[0].split(' ')
instruction[0].map! do |item|
if wires.has_key?(item.to_sym)
wires[item.to_sym]
elsif item =~ /AND|OR|NOT|LSHIFT|RSHIFT/
item
else
item.to_i
end
end
next if instruction[0].include?(nil)
if instruction[0].include?('AND')
wires[instruction[1].to_sym] = instruction[0][0] & instruction[0][2]
input.delete(instruction)
elsif instruction[0].include?('OR')
wires[instruction[1].to_sym] = instruction[0][0] | instruction[0][2]
input.delete(instruction)
elsif instruction[0].include?('NOT')
wires[instruction[1].to_sym] = instruction[0][1] ^ 65_535
input.delete(instruction)
elsif instruction[0].include?('LSHIFT')
wires[instruction[1].to_sym] = instruction[0][0] << instruction[0][2]
input.delete(instruction)
elsif instruction[0].include?('RSHIFT')
wires[instruction[1].to_sym] = instruction[0][0] >> instruction[0][2]
input.delete(instruction)
else
wires[instruction[1].to_sym] = instruction[0][0]
end
input.delete(line)
# break if i > 1000
end
puts "Part 2 Solution: #{wires[:a]}"