All examples By author By category About

tophtucker

Nearest neighbor

nearestNeighbor lets you find the closest neighbor to a given point in a two-dimensional space. Demo: click around up there.

It uses d3's voronoi geometry, but it convenient for more abstract uses where you might not want to draw anything onscreen at all. All it really adds is an algorithm from StackOverflow for finding which polygon generated by the voronoi geometry contains the point. And then it just brute-forces it. It's idiotic. At this point you might as well just brute-force distances to every neighboring point, right? But maybe I can improve it to be non-worthless. "If the polygons form a planar graph with each edge labelled with its two polygon neighbors, then one simple way is to run a semi-infinite ray up from the point until it hits its first edge. Then the relevant containing polygon is one of that edge's neighbors." OK rpi.edu, I don't know how to cast a ray until it hits its first edge.

Usage:

First, generate your neighbor-finding function.

var near = nearestNeighbor(friends)
  .x(function(d) { return d.age; })
  .y(function(d) { return d.salary; })

Then use it.

near({'age': 25, 'salary': 75000})

Now you have the person out of your friends who is closest to being 25 and having a salary of $75,000. I guess you could use the accessors to do weighting, right? But idk if...

Further reading: