当前位置: 代码迷 >> 综合 >> P5.js / processing——旅行商问题
  详细解决方案

P5.js / processing——旅行商问题

热度:18   发布时间:2023-12-07 03:01:24.0

偶然发现Daniel Shiffman老师关于旅行商问题的视频,以下是从GitHub上找到的老师的源代码,

效果图:

随机产生多个点,不断计算最短距离,待紫色线条不动,则此条线为最短路径

代码:

  js部分:

var cities = [];
var totalCities = 6;
var recordDistance;
var bestEver;function setup() {createCanvas(600,400);for (var i = 0; i < totalCities; i++) {var v = createVector(random(width), random(height));cities[i] = v;}var d = calcDistance(cities);recordDistance = d;bestEver = cities.slice();
}function draw() {background(0);fill(0); noStroke();fill(255);for (var i = 0; i < cities.length; i++) {ellipse(cities[i].x, cities[i].y, 8, 8);}stroke(255);strokeWeight(1);noFill(); beginShape();for (var i = 0; i < cities.length; i++) {vertex(cities[i].x, cities[i].y);}endShape();stroke(255, 0, 255);strokeWeight(4);noFill();beginShape();for (var i = 0; i < cities.length; i++) {vertex(bestEver[i].x, bestEver[i].y);}endShape();var i = floor(random(cities.length));var j = floor(random(cities.length));swap(cities, i, j);var d = calcDistance(cities);if (d < recordDistance) {recordDistance = d;bestEver = cities.slice();console.log(recordDistance);console.log(bestEver);}
}function swap(a, i, j) {var temp = a[i];a[i] = a[j];a[j] = temp;
}function calcDistance(points) {var sum = 0;for (var i = 0; i < points.length - 1; i++) {var d = dist(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y);sum += d;}return sum;
}

  html部分

<html>
<head><meta charset="UTF-8"><!--一个很好的免费的CDN(Content Delivery Network/内容分发网络)平台--jsDelivr,和GitHub配合使用--><script language="javascript" type="text/javascript" src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.min.js"></script><!--引用sketch.js--><script language="javascript" type="text/javascript" src="sketch.js"></script>
</head><body>
</body>
</html>

 

  相关解决方案