Skip to content

Commit 9f08806

Browse files
committed
optimise
1 parent 37766bd commit 9f08806

File tree

1 file changed

+18
-31
lines changed

1 file changed

+18
-31
lines changed

aoc-2023/day-24/src/bin/part_two.rs

Lines changed: 18 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use itertools::Itertools;
2-
use z3::ast::{Ast, Int};
2+
use z3::ast::{Ast, Int, Real};
33

44
#[aoc_runner::main(24)]
5-
fn main(input: &str) -> i64 {
5+
fn main(input: &str) -> usize {
66
let hailstones = input
77
.split('\n')
88
.map(|line| {
@@ -24,45 +24,32 @@ fn main(input: &str) -> i64 {
2424
solve(&hailstones)
2525
}
2626

27-
fn solve(hailstones: &[((f64, f64, f64), (f64, f64, f64))]) -> i64 {
28-
let cfg = z3::Config::new();
29-
let ctx = z3::Context::new(&cfg);
27+
fn solve(hailstones: &[((f64, f64, f64), (f64, f64, f64))]) -> usize {
28+
let ctx = z3::Context::new(&z3::Config::new());
3029
let s = z3::Solver::new(&ctx);
30+
let [fx, fy, fz, fdx, fdy, fdz] =
31+
["fx", "fy", "fz", "fdx", "fdy", "fdz"].map(|v| Real::new_const(&ctx, v));
3132

32-
let (fx, fy, fz) = (
33-
Int::new_const(&ctx, "fx"),
34-
Int::new_const(&ctx, "fy"),
35-
Int::new_const(&ctx, "fz"),
36-
);
37-
let (fdx, fdy, fdz) = (
38-
Int::new_const(&ctx, "fdx"),
39-
Int::new_const(&ctx, "fdy"),
40-
Int::new_const(&ctx, "fdz"),
41-
);
42-
43-
let zero = Int::from_i64(&ctx, 0);
33+
let zero = Int::from_i64(&ctx, 0).to_real();
4434
for (i, &((x, y, z), (dx, dy, dz))) in hailstones.iter().enumerate() {
45-
let (x, y, z) = (
46-
Int::from_i64(&ctx, x as _),
47-
Int::from_i64(&ctx, y as _),
48-
Int::from_i64(&ctx, z as _),
49-
);
50-
let (dx, dy, dz) = (
51-
Int::from_i64(&ctx, dx as _),
52-
Int::from_i64(&ctx, dy as _),
53-
Int::from_i64(&ctx, dz as _),
54-
);
35+
let [x, y, z, dx, dy, dz] =
36+
[x, y, z, dx, dy, dz].map(|v| Int::from_i64(&ctx, v as _).to_real());
37+
38+
let t = Real::new_const(&ctx, format!("t{i}"));
5539

56-
let t = Int::new_const(&ctx, format!("t{i}"));
5740
s.assert(&t.ge(&zero));
5841
s.assert(&((&x + &dx * &t)._eq(&(&fx + &fdx * &t))));
5942
s.assert(&((&y + &dy * &t)._eq(&(&fy + &fdy * &t))));
6043
s.assert(&((&z + &dz * &t)._eq(&(&fz + &fdz * &t))));
6144
}
6245

6346
assert_eq!(s.check(), z3::SatResult::Sat);
64-
let model = s.get_model().unwrap();
65-
let res = model.eval(&(&fx + &fy + &fz), true).unwrap();
6647

67-
res.as_i64().unwrap()
48+
let res = s
49+
.get_model()
50+
.unwrap()
51+
.eval(&(&fx + &fy + &fz), true)
52+
.unwrap();
53+
54+
res.to_string().strip_suffix(".0").unwrap().parse().unwrap()
6855
}

0 commit comments

Comments
 (0)