Skip to content

Instantly share code, notes, and snippets.

@mindoftea
Created May 10, 2014 05:50
Show Gist options
  • Save mindoftea/695cda47b5f065a7ebec to your computer and use it in GitHub Desktop.
Save mindoftea/695cda47b5f065a7ebec to your computer and use it in GitHub Desktop.
A javascript function which uses a map to efficiently search for nearby points distributed across a one-dimensional field. There is quite a high up-front cost to initializing the map, but, once that is done, each point-finding operation is extremely cheap.
var CheckPoints=function(list, spaceSize, scanSize)
{
var n,m,map;
list.sort(
function(a,b)
{
return -(a.x<b.x)+(a.x>b.x);
}
);
map={};
n=Math.floor(spaceSize/scanSize);
while(n--)
{
map[n*scanSize]=undefined;
}
n=list.length;
while(n--)
{
for(m in map)
{
if(map[m]===undefined || Math.abs(list[n].x-m)<Math.abs(list[map[m]].x-m))
{
map[m]=n;
}
}
}
return function(x)
{
var selected,n,no;
selected=[];
n=map[Math.round(x/scanSize)*scanSize];
while(1)
{
no=list[n++];
if(Math.abs(no.x-x)<scanSize/2+no.r)
{
selected.push(no);
}
else if(no.x>x)
{
break;
}
}
return selected;
}
};
var Point=function(x)
{
return {x:x,r:1};
}
var points=[];
var n=1000000;
while(n--)
{
points[n]=Point(1000*Math.random());
}
var check;
check=CheckPoints(points, 1000, 50);
// Returns the below function after 18.9 seconds.
var t=Date.now();
check(632);
print(Date.now()-t)
// Returns an array containing every point within a 25 unit radius of a point at 632 after 2 ms.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment