xxxxxxxxxx
56
let cities = {
"New York": { x: 520, y: 120 },
"Los Angeles": { x: 70, y: 370 },
"Chicago": { x: 300, y: 200 },
"Houston": { x: 250, y: 330 },
"Phoenix": { x: 120, y: 350 },
"Philadelphia": { x: 500, y: 140 },
"San Antonio": { x: 230, y: 350 },
"San Diego": { x: 60, y: 390 },
"Dallas": { x: 260, y: 310 },
"San Jose": { x: 90, y: 400 }
};
function setup() {
createCanvas(700, 600);
textSize(8);
calculateNeighbors();
}
function draw() {
background(255);
for (let city in cities) {
fill(100);
ellipse(cities[city].x, cities[city].y, 20, 20);
for (let neighbor of cities[city].neighbors) {
let neighborX = cities[neighbor].x;
let neighborY = cities[neighbor].y;
stroke(0);
line(cities[city].x, cities[city].y, neighborX, neighborY);
let midX = (cities[city].x + neighborX) / 2;
let midY = (cities[city].y + neighborY) / 2;
let distance = dist(cities[city].x, cities[city].y, neighborX, neighborY);
text(nf(distance, 0, 2), midX, midY);
}
}
noLoop(); // Static drawing
}
function calculateNeighbors() {
for (let city in cities) {
let distances = [];
for (let otherCity in cities) {
if (otherCity !== city) {
let d = dist(cities[city].x, cities[city].y, cities[otherCity].x, cities[otherCity].y);
distances.push({ city: otherCity, distance: d });
}
}
distances.sort((a, b) => a.distance - b.distance);
cities[city].neighbors = distances.slice(0, 3).map(d => d.city);
}
}