-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.js
307 lines (256 loc) · 9.35 KB
/
code.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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/* Logic */
const getKeyByValue = (object, value) => {
return Object.keys(object).find(key => object[key] === value);
}
const generateEdges = (input, ...args) => {
//Sort edges, routes goes from left to right as alphabetical order
let edges = input.toUpperCase().replace(/\s/g,'').split(',').sort();
let currentEdges = [];
let finalEdges = [];
//If ...args are not passed, return sorted edges
if (args.length===0) {
return edges;
}
//Get edges that include the given route, not sorted by given route
for (let edge of edges) {
args.reduce((prior, current) => {
if(prior!==null) {
if ( edge.includes(prior.concat(current)) ) {
currentEdges.push(edge);
}
}
return current;
}, null);
}
//Sort edges by given route not alphabetical order, the previous one will be linked to the next one
for (let arg of args) {
for (let currentEdge of currentEdges) {
if (currentEdge.charAt(0)===arg) {
finalEdges.push(currentEdge);
}
}
}
//If finalEdges don't include any of the args that route doesn't exist
for (let arg of args) {
if (! finalEdges.join().includes(arg) ) {
finalEdges = [];
}
}
return finalEdges;
}
const generateGraph = (sortedEdges, actionType, ...args) => {
let edges = [...sortedEdges];
let type = actionType;
let start = args[0];
let finish = args[1];
let routes = []; //2D array
edges.map(element => {
let children = element.split("");
routes.push(children);
});
//If sortedEdges is empty then that route doesn't exist
if (edges.length===0) {
return {};
}
let graph = {};
routes.reduce((prior, current, index) => {
//Build first node
if (prior===null) {
graph[ current[0] ] = { [ current[1] ]: Number(current[2]) };
}
//Build the other nodes
if (prior!==null) {
//If first node has more routes
if (prior[0]==current[0]) {
graph[ current[0] ] = { ...graph[ current[0] ], [ prior[1] ]: Number(prior[2]), [ current[1] ]: Number(current[2]) };
}
//If the other nodes have more routes
if (prior[0]!=current[0]) {
graph[ current[0] ] = { ...graph[ current[0] ], [ current[1] ]: Number(current[2]) };
}
//Build the previous node before the last one
if (type==='SHORT_ROUTE' && routes[routes.length-1]===current ) {
if ( graph[ current[1] ] ) {
graph[ current[0] ] = { ...graph[ current[0] ], [ `_${current[1]}` ]: Number(current[2]) };
delete graph[ current[0] ][ current[1] ];
}
}
}
return current;
}, null);
//Build last node
if (! graph[ routes[routes.length-1][1] ] ) {
graph[ routes[routes.length-1][1] ] = { };
} else {
graph[ `_${routes[routes.length-1][1]}` ] = { };
}
//Build last node for SHORT_ROUTE
if (type==='SHORT_ROUTE') {
if (start===finish) {
finish = `_${finish}`;
}
//When tap true means still in the given route
let tap = false;
let keys = Object.keys(graph);
for (let key of keys) {
if (key===start) {
tap = true;
}
if (tap===false) {
delete graph[ key ];
}
if (key===finish) {
tap = false;
}
}
let currentKeys = Object.keys(graph);
graph[ currentKeys[ currentKeys.length-1 ] ] = {}
}
return graph;
}
const findLowestCostNode = (costs, processed) => {
const knownNodes = Object.keys(costs)
//If lowest node is greater than current node, then it's not the lowest
const lowestCostNode = knownNodes.reduce((lowest, node) => {
if (lowest === null || costs[node] < costs[lowest]) {
if (!processed.includes(node)) {
lowest = node;
}
}
return lowest;
}, null);
return lowestCostNode;
}
const dijkstra = (graph) => {
//Where to start and finish
const keys = Object.keys(graph);
const values = Object.values(graph);
const start = keys[0];
let finish;
for (let value of values) {
if (Object.keys(value).length === 0 && value.constructor === Object) {
finish = getKeyByValue(graph, value);
}
}
//Initial trackedCosts
const trackedCosts = Object.assign({ [finish]: Infinity }, graph[start]);
//Initial trackedParents
const trackedParents = { [finish]: null };
for (let child in graph[start]) {
trackedParents[child] = start;
}
//If it's processed will be in this array
const processedNodes = [];
let node = findLowestCostNode(trackedCosts, processedNodes);
//Start the search
while (node) {
let costToReachNode = trackedCosts[node];
let childrenOfNode = graph[node];
for (let child in childrenOfNode) {
//Cost from lowest node to his child
let costFromNodetoChild = childrenOfNode[child]
//Cost from start node to end node
let costToChild = costToReachNode + costFromNodetoChild;
if (!trackedCosts[child] || trackedCosts[child] > costToChild) {
trackedCosts[child] = costToChild;
trackedParents[child] = node;
}
}
processedNodes.push(node);
node = findLowestCostNode(trackedCosts, processedNodes);
}
let optimalPath = [ finish ];
let parent = trackedParents[finish];
while (parent) {
optimalPath.push(parent);
parent = trackedParents[parent];
}
optimalPath.reverse();
//If finish from trackedCosts is Infinity then that route doesn't exist
const results = {
distance: (trackedCosts[finish]===Infinity) ? `No such route` : trackedCosts[finish],
path: optimalPath
};
return results.distance;
}
/* UI */
let input = window.document.getElementById('input');
let output01 = window.document.getElementById('output01');
let output02 = window.document.getElementById('output02');
let output03 = window.document.getElementById('output03');
let output04 = window.document.getElementById('output04');
let output05 = window.document.getElementById('output05');
let output06 = window.document.getElementById('output06');
let output07 = window.document.getElementById('output07');
let output08 = window.document.getElementById('output08');
let output09 = window.document.getElementById('output09');
let output10 = window.document.getElementById('output10');
let btnCalculate = window.document.getElementById('btnCalculate');
window.addEventListener('keyup', (event) => {
event.preventDefault();
if (event.keyCode===13) {
btnCalculate.click();
}
});
btnCalculate.addEventListener('click', (event) => {
event.preventDefault();
//Test input AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7
let mainEdges = generateEdges(input.value);
let mainGraph = generateGraph(mainEdges);
console.log('mnfc mainGraph ', mainGraph);
//Output #01 - Distance of route A-B-C
let edges01 = generateEdges(input.value, 'A', 'B', 'C');
let graph01 = generateGraph(edges01, 'SINGLE_ROUTE');
console.log('mnfc graph01 ', graph01);
output01.value = dijkstra(graph01);
output01.style.color = '#336df4';
output01.style.fontWeight = 'bold';
//Output #02 - Distance of route A-D
let edges02 = generateEdges(input.value, 'A', 'D');
let graph02 = generateGraph(edges02, 'SINGLE_ROUTE');
console.log('mnfc graph02 ', graph02);
output02.value = dijkstra(graph02);
output02.style.color = '#336df4';
output02.style.fontWeight = 'bold';
//Output #03 - Distance of route A-D-C
let edges03 = generateEdges(input.value, 'A', 'D', 'C');
let graph03 = generateGraph(edges03, 'SINGLE_ROUTE');
console.log('mnfc graph03 ', graph03);
output03.value = dijkstra(graph03);
output03.style.color = '#336df4';
output03.style.fontWeight = 'bold';
//Output #04 - Distance of route A-E-B-C-D
let edges04 = generateEdges(input.value, 'A', 'E', 'B', 'C', 'D');
let graph04 = generateGraph(edges04, 'SINGLE_ROUTE');
console.log('mnfc graph04 ', graph04);
output04.value = dijkstra(graph04);
output04.style.color = '#336df4';
output04.style.fontWeight = 'bold';
//Output #05 - Distance of route A-E-D
let edges05 = generateEdges(input.value, 'A', 'E', 'D');
let graph05 = generateGraph(edges05, 'SINGLE_ROUTE');
console.log('mnfc graph05 ', graph05);
output05.value = dijkstra(graph05);
output05.style.color = '#336df4';
output05.style.fontWeight = 'bold';
//Output #06 - Trips from C to C with 3 stops
output06.value = ''; //Not working
//Output #07 - Trips from A to C with 4 stops
output07.value = ''; //Not working
//Output #08 - Shortest route from A to C
let edges08 = generateEdges(input.value);
let graph08 = generateGraph(edges08, 'SHORT_ROUTE', 'A', 'C');
console.log('mnfc graph08 ', graph08);
output08.value = dijkstra(graph08);
output08.style.color = '#336df4';
output08.style.fontWeight = 'bold';
//Output #09 - Shortest route from B to B
let edges09 = generateEdges(input.value);
let graph09 = generateGraph(edges09, 'SHORT_ROUTE', 'B', 'B');
console.log('mnfc graph09 ', graph09);
output09.value = dijkstra(graph09);
output09.style.color = '#336df4';
output09.style.fontWeight = 'bold';
//Output #10 - Routes C to C distance<30
output10.value = ''; //Not working
});