O(log n) nearest neighbor search with exact Pythagorean coordinate snapping
See how Constraint Theory keeps variable character counts constant while traditional approaches grow with approximations and floating-point drift.
// Standard: Brute force search
fn find_nearest_pythagorean(
point: (f64, f64),
triples: &[(i32, i32, i32)]
) -> Option<(i32, i32, i32)> {
let mut best: Option<(i32, i32, i32)> = None;
let mut best_dist = f64::MAX;
for &(a, b, c) in triples {
let da = (point.0 - a as f64).powi(2);
let db = (point.1 - b as f64).powi(2);
let dist = (da + db).sqrt();
if dist < best_dist {
best_dist = dist; // FP drift!
best = Some((a, b, c));
}
}
best
}
// Constraint Theory: KD-tree lookup use constraint_theory::Manifold; let manifold = Manifold::pythagorean(); let nearest = manifold.find_nearest(point)?; // O(log n) vs O(n) - Done!
| Step | 1 | 10 | 100 | 1000 | 10000 |
|---|---|---|---|---|---|
| Traditional | ~400 | ~600 | ~800 | ~1000 | ~1200 |
| Constraint Theory | 90 | 90 | 90 | 90 | 90 |
| Ratio | 4.4x | 6.7x | 8.9x | 11.1x | 13.3x |
Recursively split the space by selecting median points. At each level, alternate between splitting on x-axis (vertical) and y-axis (horizontal). This creates a balanced binary tree.
Traverse down the tree to find the leaf containing the query point. Then backtrack, checking if there could be closer points on the other side of any splitting plane.
Points snap to exact Pythagorean triples (3,4,5), (5,12,13), etc. No floating-point drift. Same result on every machine, forever.