This is a little something I whipped up to quickly find the closest seeds in a Voronoi diagram.
var/minx=0,miny=0,maxx=width-1,maxy=height-1,maxd=width+height |
You start the algorithm with a list of seeds, and x and y coordinates for your target point. At the end, seeds[1] through seeds[bestn] are your closest seeds.
Taking the algorithm apart, you see that at each step, a random point from part of the list is chosen. At the head of the list there are the best points, the closest ones found. At the tail is everything that has been discarded. Every point in the active portion of the list should be within the square bounded by minx/maxx and miny/maxy.
Each iteration of the main loop is looking inside the "active square" to find points within a circle with center x,y and radius maxd. Anything that's in the square but not the circle is discarded. Whenever a new best seed is found, the max distance is recalculated and the active square is narrowed down to an even smaller square. During this process, more seeds are pushed over to the tail of the list if they don't fit the square.
This algorithm should be fairly efficient because the "rejection sort" done as the square shrinks is only O(n) complexity, where n in this case is getting smaller each time, so the overall process is roughly O(n log n) in an average case. At any given step, you have about a π/4 chance of picking a seed inside the circle--a chance that grows larger as seeds are found and discarded, so eventually you'll either find a seed inside the circle or run out of seeds to test. Depending on the new seed you find, the circle could get a little smaller or a lot smaller, but anything you've already rejected stays rejected.
Lummox JR
