Skip to content

Commit

Permalink
reduce computation steps
Browse files Browse the repository at this point in the history
  • Loading branch information
semibran committed Mar 6, 2018
1 parent 45c9731 commit 4be0b39
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 27 deletions.
2 changes: 1 addition & 1 deletion demo/src/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const height = window.innerHeight

let graph = {
edges: [],
nodes: new Array(128)
nodes: new Array(512)
.fill()
.map(_ => {
let direction = Math.random() * 2 * Math.PI
Expand Down
51 changes: 25 additions & 26 deletions lib/graph-mst.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,38 @@
module.exports = function span(graph) {
var prospects = graph.edges.slice()
var edges = []
var tree = {
nodes: graph.nodes.slice(),
edges: []
}
var edges = graph.edges
.slice()
.sort(function (a, b) { return a.weight - b.weight })
var indices = [ 0 ]
while (prospects.length && indices.length < graph.nodes.length) {
var shortest = null
var target = null
var index = null
for (var i = 0; i < indices.length; i++) {
var o = indices[i]
for (var j = 0; j < prospects.length; j++) {
var edge = prospects[j]
var a = edge.endpoints[0]
var b = edge.endpoints[1]
while (indices.length < graph.nodes.length) {
for (var i = 0; i < edges.length; i++) {
var edge = edges[i]
var a = edge.endpoints[0]
var b = edge.endpoints[1]
for (var j = 0; j < indices.length; j++) {
var o = indices[j]
var t = -1
if (a === o) {
t = b
} else if (b === o) {
t = a
}
if (t === -1 || indices.indexOf(t) !== -1) continue
if (!shortest || edge.weight < shortest.weight) {
shortest = edge
target = t
index = j
if (t !== -1) {
break
}
}
if (t !== -1) {
if (indices.indexOf(t) === -1) {
indices.push(t)
tree.edges.push(edge)
}
edges.splice(i, 1)
break
}
}
if (shortest) {
edges.push(shortest)
indices.push(target)
prospects.splice(index, 1)
}
}
return {
nodes: graph.nodes.slice(),
edges: edges
}
return tree
}

0 comments on commit 4be0b39

Please sign in to comment.