From 0726c374f25444a593c4109c66930a3576cea56a Mon Sep 17 00:00:00 2001 From: Andrew Tomaka Date: Fri, 27 Dec 2024 22:54:11 -0500 Subject: [PATCH] Day twenty-four Part two --- 24/main.rb | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) mode change 100644 => 100755 24/main.rb diff --git a/24/main.rb b/24/main.rb old mode 100644 new mode 100755 index 735b6e6..080dcb2 --- a/24/main.rb +++ b/24/main.rb @@ -10,6 +10,46 @@ input[...split] .map { _1.split(": ") } .each { wires[_1] = _2.to_i } +flipped = Set.new +gates.select { _1.match?(/XOR/) }.each do |gate| + in1, op, in2, out = gate.scan(/([a-z0-9]{3}) ([A-Z]+) ([a-z0-9]{3}) -> ([a-z0-9]{3})/).first + + if op == "XOR" && [in1, in2].map { _1[0] }.sort != %w[x y] + if !out.start_with?("z") + flipped << out + end + end +end + +# 45 is a half adder +(0..44).each do |num| + z = "z#{'%02d' % num}" + gate = gates.find { _1.match?(/#{z}$/) } + in1, op, in2, out = gate.scan(/([a-z0-9]{3}) ([A-Z]+) ([a-z0-9]{3}) -> ([a-z0-9]{3})/).first + if op != "XOR" + flipped << z + end +end + +gates.select { _1.match?(/AND/) }.each do |gate| + in1, op, in2, out = gate.scan(/([a-z0-9]{3}) ([A-Z]+) ([a-z0-9]{3}) -> ([a-z0-9]{3})/).first + + if [in1, in2].map { _1[0] }.sort == %w[x y] && in1 != "x00" + if gates.find { _1.match?(/#{out}/) && _1.match?(/ OR /) }.nil? + flipped << out + end + end +end + +gates.select { _1.match?(/XOR/) }.each do |gate| + in1, op, in2, out = gate.scan(/([a-z0-9]{3}) ([A-Z]+) ([a-z0-9]{3}) -> ([a-z0-9]{3})/).first + + if [in1, in2].map { _1[0] }.sort == %w[x y] && in1 != "x00" && in1 != "y00" + if gates.count { _1.match?(/#{out}/) && _1.match?(/ XOR /) } != 2 + flipped << out + end + end +end i = 0 until gates.empty? @@ -44,6 +84,8 @@ z = wires.select { _1.match?(/^z/) }.sort_by(&:first).map { _1.last.to_s }.rever zi = z.to_i(2) p zi +p flipped.sort.join(",") + __END__ x00: 0 x01: 1 @@ -64,4 +106,3 @@ x02 AND y02 -> z01 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z00 -