Skip to content

Commit abcb023

Browse files
committed
day 24, part 1 (refactor)
Move case statement to parsing and use a lambda for the work later.
1 parent 3edac6a commit abcb023

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

2024/ruby/day24.rb

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,25 @@ def part1
1919
known_wires[wire] = signal.to_i
2020
when /-\>/
2121
input1, gate, input2, wire = line.scan(/\w+/)
22-
to_be_determined[wire] = { inputs: [input1, input2], gate: gate }
22+
op = case gate
23+
when 'AND' ; :&
24+
when 'OR' ; :|
25+
when 'XOR' ; :^
26+
else ; raise "lolwut: unknown gate #{gate}"
27+
end
28+
to_be_determined[wire] = {
29+
inputs: [input1, input2],
30+
proc: -> { [input1, input2].map { known_wires[_1] }.reduce(&op) }
31+
}
2332
end
2433
end
2534

2635
while to_be_determined.keys.any? {|wire| wire.start_with?('z') } do
2736
puts to_be_determined.keys.inspect if ENV['DEBUG']
2837
to_be_determined
29-
.select {|wire, data| data[:inputs].all? {|input| known_wires.keys.include?(input) } }
30-
.each do |wire, data|
31-
known_wires[wire] =
32-
case data[:gate]
33-
when 'AND' ; known_wires[data[:inputs][0]] & known_wires[data[:inputs][1]]
34-
when 'OR' ; known_wires[data[:inputs][0]] | known_wires[data[:inputs][1]]
35-
when 'XOR' ; known_wires[data[:inputs][0]] ^ known_wires[data[:inputs][1]]
36-
else ; raise "lolwut: unknown gate #{data[:gate]}"
37-
end
38+
.select {|wire, gate| gate[:inputs].all? { known_wires.key?(_1) } }
39+
.each do |wire, gate|
40+
known_wires[wire] = gate[:proc].call
3841
to_be_determined.delete(wire)
3942
end
4043
end

0 commit comments

Comments
 (0)