Repository navigation
Expand file tree
/
Copy pathMST.js
More file actions
92 lines (78 loc) · 2.13 KB
/
Copy pathMST.js
File metadata and controls
92 lines (78 loc) · 2.13 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Canvas setup
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Variables
var vertices = []
var visited = []
var unvisited = []
var vertex_radius = 3
var number_of_vertices = 1000
var line_width = 1
/**
* First thing we want is when we click somewhere, is to draw a circle and add its position to
* our list of vertices.
*
* The algorithm is essentially...
*
* keep track of unreached
* */
function setup() {
for (var i = 0; i < number_of_vertices; i++) {
let x = Math.floor(Math.random() * canvas.width)
let y = Math.floor(Math.random() * canvas.height)
vertices.push([x,y])
unvisited.push([x,y])
}
}
function drawCircle(x , y) {
ctx.beginPath();
ctx.arc(x, y, vertex_radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}
function drawVertices() {
for (var i = 0; i < vertices.length; i++) {
drawCircle(vertices[i][0], vertices[i][1])
}
}
function draw() {
drawVertices();
}
function distance(a, b) {
var c = a[0]-b[0]
var d = (b[0]-b[1])
return Math.sqrt( c*c + d*d );
}
function prims() {
visited.push(vertices[0]);
unvisited.splice(0, 1)
var u_index = 0;
var r_index = 0;
while (unvisited.length > 0) {
var min_total_dist = 100000;
for (var i = 0; i < visited.length; i++) {
for (var j = 0; j < unvisited.length; j++) {
if (distance(visited[i], unvisited[j]) < min_total_dist) {
min_total_dist = distance(visited[i], unvisited[j]);
u_index = j;
r_index = i;
}
}
}
// set line stroke and line width
ctx.strokeStyle = 'white';
ctx.lineWidth = line_width;
// draw a red line
ctx.beginPath();
ctx.moveTo(visited[r_index][0], visited[r_index][1]);
ctx.lineTo(unvisited[u_index][0], unvisited[u_index][1]);
ctx.stroke();
visited.push(unvisited[u_index]);
unvisited.splice(u_index, 1);
}
}
setup()
draw()
prims()