如何在对象数组中添加与对象关联的值?

时间:2014-12-15 21:54:57

标签: javascript dijkstra

我试图找出如何将通过每个节点/顶点所采用的路线的弧/重量值加在一起,使用var ShortestPath(朝向代码的底部),我已经多年来坚持这一点,非常感谢提前。



function PriorityQueue() {
this._nodes = [];

this.enqueue = function (priority, key) {
    this._nodes.push({ key: key, priority: priority });
    this.sort();
}
this.dequeue = function () {
    return this._nodes.shift().key;
}
this.sort = function () {
    this._nodes.sort(function (a, b) {
        return a.priority - b.priority;
    });
}
this.isEmpty = function () {
    return !this._nodes.length;
}
}
  //Pathfinding starts here
  //Create graph object
 function Graph() {
// .js infinitiy variable
var INFINITY = 1 / 0;

//list to hold all townsville stations and arc values
this.vertices = {};

//function to add a vertex to the vertices list
this.addVertex = function (name, arc) {
    this.vertices[name] = arc;
}

//Create shortestPath function that takes a start and finish point
this.shortestPath = function (start, finish) {
    var nodes = new PriorityQueue(),
        distances = {},
        previous = {},
        path = [],
        smallest, vertex, neighbor, alt;

    for (vertex in this.vertices) {
        //check if its the starting vertices
        if (vertex === start) {
            //it is, set arc weight to 0
            distances[vertex] = 0;
            nodes.enqueue(0, vertex);
        }
        else {
            distances[vertex] = INFINITY;
            nodes.enqueue(INFINITY, vertex);
        }

        previous[vertex] = null;
    }
    //while there are nodes in the node array
    while (!nodes.isEmpty()) {
        smallest = nodes.dequeue(); //remove the fist node from the stack
        //if its not the destination node
        if (smallest === finish) {
            path;

            while (previous[smallest]) {
                path.push(smallest);
                smallest = previous[smallest];
            }

            break;
        }

        if (!smallest || distances[smallest] === INFINITY) {
            continue;
        }

        for (neighbor in this.vertices[smallest]) {
            alt = distances[smallest] + this.vertices[smallest][neighbor];

            if (alt < distances[neighbor]) {
                distances[neighbor] = alt;
                previous[neighbor] = smallest;

                nodes.enqueue(alt, neighbor);
            }
        }
    }
    return path;
  }
 }

function ProcessValues() {

var graph = new Graph();

//town map names and arc weights/values      
graph.addVertex('Eden-Broadway', { 'Rupert-Street': 15 });
graph.addVertex('Rupert-Street', { 'Arcrub-Road': 5, 'Westbury-Farm': 5, 'Eden-Broadway': 15 });
graph.addVertex('Blacktown', { 'Rupert-Street': 5, 'Virginia': 15 });
graph.addVertex('Virginia', { 'Blacktown': 15, 'Draft': 5 });
graph.addVertex('Draft', { 'Virginia': 5, 'Effing': 10 });
graph.addVertex('Effing', { 'Draft': 10 });
graph.addVertex('Arcrub-Road', { 'Rupert-Street': 5, 'Doyle-Place': 10 });
graph.addVertex('Doyle-Place', { 'Arcrub-Road': 10, 'Wimbley': 10, 'Manchester-Road': 10, 'Princes-Park': 5 });
graph.addVertex('Manchester-Road', { 'Doyle-Place': 10, 'Draft': 5 });
graph.addVertex('Wimbley', { 'Doyle-Place': 10 });
graph.addVertex('Princes-Park', { 'Doyle-Place': 5, 'Cambridge-Circus': 10 });
graph.addVertex('Cambridge-Circus', { 'Princes-Park': 10, 'Statue': 5 });
graph.addVertex('Statue', { 'Cambridge-Circus': 5, 'Hippo-Green': 10, 'Greyfriars': 5, 'Castle-Portway': 5 });
graph.addVertex('Hippo-Green', { 'Statue': 10, 'The-Angel': 10 });
graph.addVertex('The-Angel', { 'Hippo-Green': 10 });
graph.addVertex('Westbury-Farm', { 'Rupert-Street': 5, 'Greyfriars': 10 });
graph.addVertex('Greyfriars', { 'Westbury-Farm': 10, 'Statue': 5 });
graph.addVertex('Castle-Portway', { 'Statue': 5, 'Draft': 5 });

//Get start/end points
var startPoint = slStart.value;
var endPoint = slEnd.value;

// To display we reverse the path and prepend the first node
var ShortestPath = graph.shortestPath(startPoint, endPoint).concat([startPoint]).reverse();


$("#txtShortestPath").val(ShortestPath);
//$("#txtMinutes").val(MinsTaken); //TODO
}

$('#start').on('click', ProcessValues);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Start point: <input id="slStart" value="Eden-Broadway"></label>
<label>Start point: <input id="slEnd" value="Statue"></label>
</div>
<button id="start">Start</button>
<div>
<label>Shortest path: <input id="txtShortestPath"></label><br />
<label>Minutes taken: <input id="txtMinutes"></label>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

距离在shortestPath()函数内部已知,就在它返回路径本身之前。此时,您只需添加距离:

return {
  path: path,
  distance: distances[finish]
};

然后,在来电方面:

var data = graph.shortestPath(startPoint, endPoint)
var ShortestPath = data.path.concat([startPoint]).reverse();
var MinsTaken = data.distance;