-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra_algo.js
110 lines (102 loc) · 1.5 KB
/
dijkstra_algo.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
// dijkstra algo
function parseEquation(str) {
const result = [];
let numBuf = '';
for (let i = 0; i < str.length; i += 1) {
const cur = str[i];
const isNum = Number.isInteger(parseInt(cur, 10));
if (isNum) {
// number
numBuf += cur;
} else {
// not num
if (numBuf) {
result.push(numBuf);
numBuf = '';
}
result.push(cur);
}
}
return result;
}
function dijkstra(input) {
const operands = [];
const operators = [];
for (let i = 0; i < input.length; i++) {
const cur = input[i];
if (cur === '(') {
continue;
} else if (cur === ')') {
const second = operands.pop();
const first = operands.pop();
const operator = operators.pop();
const result = eval(`(${first} ${operator} ${second})`);
operands.push(String(result));
} else if (!Number.isInteget(parseInt(cur, 10))) {
// operand
operators.push(cur);
} else {
// number
operands.push(cur);
}
}
return operands.pop();
}
const numStr = [
'(',
'(',
'(',
'4',
'+',
'12',
')',
'*',
'(',
'5',
'-',
'3',
')',
')',
].join('');
console.log(dijkstra(parseEquation(numStr)));
console.log(dijkstra([
'(',
'(',
'(',
'4',
'+',
'2',
'+',
'2',
')',
'*',
'(',
'5',
'-',
'3',
')',
')',
]));
console.log(dijkstra([
'(',
'(',
'(',
'4',
'+',
'2',
')',
'*',
'(',
'5',
'-',
'3',
')',
')',
'/',
'(',
'6',
'-',
'3',
')',
')',
]));