-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathgraph.js
55 lines (49 loc) · 1.23 KB
/
graph.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
class Node {
constructor(value, index) {
this.value = value;
this.index = index;
this.connections = [];
}
}
class DiGraph {
constructor(items) {
// Assumes `items` is already sorted
this.items = items.map((v, i) => new Node(v, i));
this.buildEdges();
}
buildEdges() {
for (let i = 0; i < this.items.length; i++) {
let current = this.items[i];
for (let n = 1; n <= 3; n++) {
let next = this.items[i + n];
if (!next) break;
if (next.value - current.value <= 3) {
current.connections.push(next);
}
}
}
}
/**
* Recursive way to count the number of unique paths from one
* index within a directed graph to another.
*
* @returns {Number}
*/
countPathsUtil(current_index, destination_index, path_count) {
// If current vertex is same as destination, then increment count
if (current_index === destination_index) {
path_count++;
} else {
let node = this.items[current_index];
for (let connection of node.connections) {
path_count = this.countPathsUtil(connection.index, destination_index, path_count);
}
}
return path_count;
}
countPaths() {
let path_count = this.countPathsUtil(0, this.items.length - 1, 0);
return path_count;
}
}
module.exports = { Node, DiGraph };