Point Heap
by skibulk
HTML
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
CSS
span {
position: absolute;
width: 3px;
height: 3px;
background: gray;
}
JavaScript
/*
Challenge: consecutive points in a line
'points': {
'point1': {x: 0, y: 0},
'group1': {
...
},
'point2': {x: 0, y: 0},
'group2': {
...
}
}
*/
var points = {};
for (i = 0; i < 500; i++) {
insert({
x: Math.floor(Math.random() * 1000),
y: Math.floor(Math.random() * 1000)
}, points);
}
function insert(p0, group) {
if ( group.point2 )
{
var d1 = dist_squared( p0.x, p0.y, group.point1.x, group.point1.y );
var d2 = dist_squared( p0.x, p0.y, group.point2.x, group.point2.y );
if ( d1 < d2 )
{
insert( p0, group.group1 );
group.count1++;
}
else
{
insert( p0, group.group2 );
group.count2++;
}
}
else if ( group.point1 )
{
group.point2 = p0;
group.group2 = {};
group.count2 = 0;
}
else
{
group.point1 = p0;
group.group1 = {};
group.count1 = 0;
}
}
function dist_squared( x1, y1, x2, y2 ) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
console.log(points);
/*
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black'];
for (i = 0; i < data.length; i++) {
for (j = 0; j < data[i].length; j++) {
$("<span></span>")
.css('left', data[i][j].x)
.css('top', data[i][j].y)
.css( 'background', colors[i] )
.appendTo('body');
}
}
*/