Skip to content

Commit 67c0928

Browse files
committed
Factor out solve function
1 parent 53c5adb commit 67c0928

File tree

1 file changed

+22
-18
lines changed

1 file changed

+22
-18
lines changed

day24/src/day24.cr

+22-18
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,27 @@ def translate_to_dot(vars : Vars, circuit : Circuit) : String
2727
].join("\n")
2828
end
2929

30+
def solve(vars : Vars, circuit : Circuit) : Int
31+
z3_src = translate_to_z3(vars, circuit)
32+
33+
z3_proc = Process.new("z3", ["-smt2", "-in"], input: :pipe, output: :pipe)
34+
z3_proc.input.puts(z3_src)
35+
z3_proc.input.close
36+
37+
z3_output = z3_proc.output.gets_to_end.gsub("\n", "")
38+
output_vars = [] of Tuple(String, Int64)
39+
z3_output.scan(/\(define-fun\s+(\w+)\s+\(\)\s+\(_\s+BitVec\s+\d+\)\s+#[xb](\d+)\)/).each do |match|
40+
output_vars << {match[1], match[2].to_i64}
41+
end
42+
output_vars.sort!
43+
44+
output_vars
45+
.select { |v| v[0].starts_with?('z') }
46+
.map { |v| v[1] }
47+
.reverse
48+
.reduce(0_i64) { |acc, b| (acc << 1) | b }
49+
end
50+
3051
if ARGV.size == 0
3152
puts "Usage: day24 [--dump-dot] [--dump-z3] <path to input>"
3253
exit 1
@@ -51,23 +72,6 @@ if flags.includes?("--dump-dot")
5172
elsif flags.includes?("--dump-z3")
5273
puts translate_to_z3(vars, circuit)
5374
else
54-
z3_src = translate_to_z3(vars, circuit)
55-
56-
z3_proc = Process.new("z3", ["-smt2", "-in"], input: :pipe, output: :pipe)
57-
z3_proc.input.puts(z3_src)
58-
z3_proc.input.close
59-
60-
z3_output = z3_proc.output.gets_to_end.gsub("\n", "")
61-
output_vars = [] of Tuple(String, Int64)
62-
z3_output.scan(/\(define-fun\s+(\w+)\s+\(\)\s+\(_\s+BitVec\s+\d+\)\s+#[xb](\d+)\)/).each do |match|
63-
output_vars << {match[1], match[2].to_i64}
64-
end
65-
output_vars.sort!
66-
67-
part1 = output_vars
68-
.select { |v| v[0].starts_with?('z') }
69-
.map { |v| v[1] }
70-
.reverse
71-
.reduce(0_i64) { |acc, b| (acc << 1) | b }
75+
part1 = solve(vars, circuit)
7276
puts "Part 1: #{part1}"
7377
end

0 commit comments

Comments
 (0)