KD-Tree Spatial Indexing

O(log n) nearest neighbor search with exact Pythagorean coordinate snapping

Click to add Pythagorean points
0
Points
0
Tree Nodes
0
Max Depth
0
Comparisons

Point Management

Tree Operations

Query Operations

Animation

Code Comparison: Constraint Theory vs Traditional

See how Constraint Theory keeps variable character counts constant while traditional approaches grow with approximations and floating-point drift.

Traditional Approach ~400 chars
// 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
}
Complexity: O(n) | Uses floating-point approximations
Constraint Theory ~90 chars
// 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!
Complexity: O(log n) | Exact integer coordinates

Variable Character Growth Over Simulation Steps

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
Traditional: grows with approximations Constraint Theory: stays exact

How KD-Tree Works

1. Build Phase

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.

2. Nearest Neighbor

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.

3. Pythagorean Snapping

Points snap to exact Pythagorean triples (3,4,5), (5,12,13), etc. No floating-point drift. Same result on every machine, forever.