Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created May 27, 2014 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1995eaton/375148b95037c2dc9305 to your computer and use it in GitHub Desktop.
Save 1995eaton/375148b95037c2dc9305 to your computer and use it in GitHub Desktop.
/r/dailyprogrammer problem #163 [hard + challenge]
function intersecting(a, b, c, d) {
var intersection = [((a[0] * b[1] - a[1] * b[0]) * (c[0] - d[0]) - (a[0] - b[0]) * (c[0] * d[1] - c[1] * d[0])) /
((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0])),
((a[0] * b[1] - a[1] * b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] * d[1] - c[1] * d[0])) /
((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]))];
function between(a, b, c) {
return c >= Math.min(a, b) && c <= Math.max(a, b);
}
if (between(a[0], b[0], intersection[0]) &&
between(c[0], d[0], intersection[0]) &&
between(a[1], b[1], intersection[1]) &&
between(c[1], d[1], intersection[1])) {
return intersection;
}
return false;
}
var Points = {
a: [[-2.5, 0.5], [3.5, 0.5]],
b: [[-2.23, 99.99], [-2.10, -56.23]],
c: [[-1.23, 99.99], [-1.1, -56.23]],
d: [[100.1, 1000.34], [2000.23, 2100.23]],
e: [[1.5, -1], [1.5, 1]],
f: [[2, 2], [3, 2]],
g: [[2.5, 0.5], [2.5, 2]]
};
var intersectionSegments = [];
for (var c in Points) {
var p = Points[c];
var n = false;
for (var c2 in Points) {
if (c !== c2) {
if (n) {
var p2 = Points[c2];
var i;
if ((i = intersecting(p[0], p[1], p2[0], p2[1]))) {
var m = [c, c2].sort().join(" ") + " at [" + i.join(", ") + "]";
if (intersectionSegments.indexOf(m) === -1) {
intersectionSegments.push(m);
}
}
}
} else {
n = true;
}
}
}
console.log(intersectionSegments.join("\n"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment