-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
73 lines (58 loc) · 1.29 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var cities = [];
var totalCities = 8;
var recordDistance;
var bestEver;
function setup() {
createCanvas(1200, 600);
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(200);
fill(255);
for (var i = 0; i < cities.length; i++) {
ellipse(cities[i].x, cities[i].y, 8, 8);
}
stroke(255);
strokeWeight(0.5);
noFill();
beginShape();
for (var i = 0; i < cities.length; i++) {
vertex(cities[i].x, cities[i].y);
}
endShape();
stroke(94, 168, 96);
strokeWeight(5);
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();
}
}
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;
}