forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22_3_optimizing.js
More file actions
50 lines (45 loc) · 1.32 KB
/
22_3_optimizing.js
File metadata and controls
50 lines (45 loc) · 1.32 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
function withIDs(graph) {
for (var i = 0; i < graph.length; i++) graph[i].id = i;
return graph;
}
var graph = withIDs(treeGraph(8, 5));
function findPath_ids(a, b) {
var work = [[a]];
var seen = Object.create(null);
for (var i = 0; i < work.length; i++) {
var cur = work[i], end = cur[cur.length - 1];
if (end == b) return cur;
end.edges.forEach(function(next) {
if (!seen[next.id]) {
seen[next.id] = true;
work.push(cur.concat([next]));
}
});
}
}
var startTime = Date.now();
console.log(findPath_ids(graph[0], graph[graph.length - 1]).length);
console.log("Time taken with ids:", Date.now() - startTime);
function listToArray(list) {
var result = [];
for (var cur = list; cur; cur = cur.via)
result.unshift(cur.last);
return result;
}
function findPath_list(a, b) {
var work = [{last: a, via: null}];
var seen = Object.create(null);
for (var i = 0; i < work.length; i++) {
var cur = work[i];
if (cur.last == b) return listToArray(cur);
cur.last.edges.forEach(function(next) {
if (!seen[next.id]) {
seen[next.id] = true;
work.push({last: next, via: cur});
}
});
}
}
var startTime = Date.now();
console.log(findPath_list(graph[0], graph[graph.length - 1]).length);
console.log("Time taken with ids + lists:", Date.now() - startTime);