I have a problem with an algorithm I'm trying to solve, i have a list of points I'm trying to check for collision, I have the general idea probably using some pytagoras, however my main problem is the efficiencie of the algorithm, cause I need to check if to rect intersect only in one axis, lets say I have a rect in point (0,100), and other in point (300, 100), both are in y=100, so for my app I decide they collide, now how I can check if any of the rects collide with any of the rest?
My first attempt was to have a loop the check for each rect I add if the new rect collide with the rest, but I think is wrong, cause if i have 100 rects, i will need to check of the first collide with the other 99, and each of them if they collide with the rest.
I'm pretty sure the loop will increase exponentially wich is bad, so can someone please point me in the right direction of how will be the best efficiencie way of checking, thanks!
EDIT 22-oct-13 using @John Phu Nguyen function
var events = [ {start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670} ];
//each start and end props are y coordinates, basically where the rect start and ends
function layOutDay(events) {
//console.log(events);
var events_container = document.querySelector('.events-col');
var frag = document.createDocumentFragment();
for(var i=0; i<events.length; i++){
//console.log(events[i].start);
var top = events[i].start;
var bottom = events[i].end-events[i].start;
var event = createEventDOM();
var gutter = event.querySelector('.gutter');
event.style.top = top + 'px';
event.style.height = gutter.style.height = bottom + 'px';
if(y_coords.indexOf(top) === -1 && y_coords.indexOf(bottom) === -1){
y_coords.push(top);
y_coords.push(bottom);
y_coords.sort();
event.style.left = '10px';
console.log('NO collision', top, bottom);
}else{
console.log('collision', top, bottom);
event.style.width = '250px';
event.style.left = '220px';
}
frag.appendChild(event);
}
events_container.appendChild(frag);
}
so running the function I got 2 rects collisioning, but there are 3 not 2, I need to know who is collisioning with who to move the rects next each other in the x axis!
Here is a screenshot of what I'm trying to do
probably is a tweak but I can't found it, any help is much appreciated, thanks!!!