Working Code: http://jsfiddle.net/sXbRK/
I have various line segments and each has its own ID. I know which ones cross each other.
Now, I need to push the ID of those overlapping line segments into new arrays.
I don't care for the line segments that don't cross each other.
How do I do push the line segment IDs that cross each other into their own array?
// New arrays of overlapping IDs
e.g. Array A = [1,2,3];
Array B = [7,8,12];
Array C = [14,15];
Here's what I have so far and don't forget to check the work-in-progress code on jsFiddle:
function cross( ls )
{
var len = ls.length;
for(var a=0; a < len - 1; a++)
{
for(var b=a+1; b < len; b++)
{
var A = ls[a],
B = ls[b],
combine = [],
overlappers = [];
if
(
(A.start <= B.start && (A.start + A.end) >= B.start)
||
(A.start <= A.start && (B.start + B.end) >= A.start)
)
{
// Add overlapping elements to arrays
overlappers.push(A.id,B.id);
// Create arrays for line segments that overlap each other
combine[a] = new Array(overlappers);
document.write('Array' + [a] + ' ==> ' + combine[a] + '<br />');
}
}
}
}
// Test data
var lineSegments = [
{id:'1', start:0, end:50},
{id:'2', start:0, end:50},
{id:'3', start:0, end:50},
{id:'4', start:100, end:50},
{id:'5', start:2开发者_JS百科00, end:50},
{id:'6', start:300, end:50},
{id:'7', start:900, end:50},
{id:'8', start:900, end:50},
{id:'9', start:600, end:50},
{id:'10', start:700, end:50},
{id:'11', start:800, end:50},
{id:'12', start:900, end:50},
{id:'13', start:1000, end:50},
{id:'14', start:1100, end:50},
{id:'15', start:1100, end:50}
];
// Execute function
cross(lineSegments);
Please help with some ideas. Thank you!
Try:
var lineSegments = [
{id:'1', start:0, end:50},
{id:'2', start:0, end:50},
{id:'3', start:0, end:50},
{id:'4', start:100, end:50},
{id:'5', start:200, end:50},
{id:'6', start:300, end:50},
{id:'7', start:900, end:50},
{id:'8', start:900, end:50},
{id:'9', start:600, end:50},
{id:'10', start:700, end:50},
{id:'11', start:800, end:50},
{id:'12', start:900, end:50},
{id:'13', start:1000, end:50},
{id:'14', start:1100, end:50},
{id:'15', start:1100, end:50}
];
function fixSense(line) {
if (line.start > line.end) {
var t = line.start;
line.start = line.end;
line.end = t;
}
return line;
}
function getCrossingLines(lines) {
var a, b;
var overlappers = [], combined = [];
// for each line
for (var i=0, iLen=lines.length - 1; i<iLen; i++) {
a = fixSense(lines[i]);
// for every other line
for (var j=i+1, jLen=lines.length; j<jLen; j++) {
b = fixSense(lines[j]);
if ( (a.start <= b.start && a.end >= b.end) ||
(a.start <= b.start && a.end >= b.end) ||
(a.start <= b.end && a.end >= b.end) ) {
overlappers.push(a.id, b.id);
combined.push([a.id, b.id]);
}
}
}
console.log('combined: ' + combined);
}
getCrossingLines(lineSegments);
精彩评论