xxxxxxxxxx
96
let points = [];
let path = [];
function setup() {
createCanvas(400, 400);
strokeWeight(3); // Thicker lines for visibility
// Generate 30 random points
for (let i = 0; i < 30; i++) {
points.push(createVector(random(width), random(height)));
}
// Find the path by selecting the closest point at each step
path.push(points[0]);
let remaining = points.slice(1); // All points except the first one
while (remaining.length > 0) {
let current = path[path.length - 1]; // Last point added to the path
let closestIndex = findClosestPoint(current, remaining);
path.push(remaining[closestIndex]);
remaining.splice(closestIndex, 1); // Remove the selected point from remaining
}
}
function draw() {
background(255);
// Draw the line segments, checking for intersections
for (let i = 0; i < path.length - 1; i++) {
let hasIntersection = false;
// Check for intersections with non-neighbouring segments
for (let j = 0; j < path.length - 1; j++) {
if (i !== j && Math.abs(i - j) > 1 && segmentsIntersect(path[i], path[i + 1], path[j], path[j + 1])) {
hasIntersection = true;
break;
}
}
// Draw the segment in red if it has an intersection, else random color
if (hasIntersection) {
stroke(255, 0, 0); // Red for intersection segments
} else {
stroke(random(255), random(255), random(255)); // Random color for non-intersecting segments
}
line(path[i].x, path[i].y, path[i + 1].x, path[i + 1].y);
}
// Draw the points for reference (optional)
fill(0);
noStroke();
for (let p of points) {
ellipse(p.x, p.y, 8, 8); // Draw points as small circles
}
}
// Function to find the closest point to the current point
function findClosestPoint(current, points) {
let closestIndex = 0;
let closestDist = dist(current.x, current.y, points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
let d = dist(current.x, current.y, points[i].x, points[i].y);
if (d < closestDist) {
closestDist = d;
closestIndex = i;
}
}
return closestIndex;
}
// Function to detect if two segments intersect
function segmentsIntersect(p1, p2, q1, q2) {
let o1 = orientation(p1, p2, q1);
let o2 = orientation(p1, p2, q2);
let o3 = orientation(q1, q2, p1);
let o4 = orientation(q1, q2, p2);
// General case: if the orientations are different, the segments intersect
if (o1 != o2 && o3 != o4) {
return true;
}
return false;
}
// Function to calculate the orientation of three points
function orientation(p, q, r) {
let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // Collinear
return (val > 0) ? 1 : 2; // Clockwise or counterclockwise
}