-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver.js
More file actions
executable file
·380 lines (320 loc) · 9.79 KB
/
solver.js
File metadata and controls
executable file
·380 lines (320 loc) · 9.79 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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
solver.js
By Charles Boyd <charlesboyd.me>
Portions adapted from geeksforgeeks.org/expression-evaluation
Can be used as a node.js script or included in a webpage.
See readme.txt for more info.
*/
Array.prototype.peek = function(){
if(this.length<1){
return false;
}
return this[this.length-1];
};
Array.prototype.empty = function(){
return this.length===0;
};
var solver = (function(){
function isNumericString(str){
return !isNaN(str) && str.length > 0;
}
function isLetterChar(str) {
return str.match(/[a-z]/i)!==null;
}
function isOpToken(str){
var opTokens = ['+', '-', '*', '/', '&', '|', '=', '~', '!', '^', '>'];
return opTokens.indexOf(str)!==-1;
}
function isValidEx(ex){
if(typeof(ex)!=='string'){
return false;
}
//TODO!
return true;
}
function checkValidEx(ex){
if(isValidEx(ex)){
return true;
}else{
throw new TypeError("The expression provided is not valid.");
}
}
var echo = function(str){
console.log(str);
};
var overrideEchoFunction = function(f){
if(typeof(f)!=='function'){
throw new TypeError('Funcion override must be a function.');
}
echo = f;
};
var varStore;
function resetVarStore(){
varStore = {
T: 1,
F: 0
};
}
resetVarStore();
function varLookup(varLetter){
if(typeof(varLetter)!=='string' || varLetter.length!==1){
return false;
}
varLetter = varLetter.toUpperCase();
if(varStore[varLetter]!==undefined){
return varStore[varLetter];
}else{
return 0;
}
}
function setVar(varLetter, value){
if(typeof(varLetter)!=='string' || varLetter.length!==1){
throw new TypeError("varLetter must be a single letter A-Z");
}
if(value==='T' || value==='t'){
value = 1;
}
if(value==='F' || value==='f'){
value = 0;
}
if(typeof(value)!=='number'){
throw new TypeError("Value must be a number or either T or F");
}
varLetter = varLetter.toUpperCase();
varStore[varLetter] = value;
return true;
}
function printVarStore(){
echo(varStore);
}
function getVarStore(){
return varStore;
}
function getListOfVars(ex){
var arr=[];
var i;
for(i=0; i<ex.length; i++){
var cchar = ex.charAt(i);
if(isLetterChar(cchar)){
cchar = cchar.toUpperCase();
if(arr.indexOf(cchar)===-1){
arr.push(cchar);
}
}
}
return arr;
}
// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
function hasPrecedence(/*char*/ op1, /*char*/ op2){
if (op2 === '(' || op2 === ')'){
return false;
}
if ((op1 === '*' || op1 === '/') && (op2 === '+' || op2 === '-')){
return false;
}else{
return true;
}
}
function boolToInt(boolVal){
if(boolVal){
return 1;
}else{
return 0;
}
}
// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
function applyOp(/* char */ op, /*int*/ b, /*int*/ a){
switch (op){
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b === 0){
throw new Error("Cannot divide by zero");
}else{
return a / b;
}
case '^':
return Math.pow(a, b);
case '&':
return boolToInt(a!==0 && b!==0);
case '|':
return boolToInt(a!==0 || b!==0);
case '>':
return boolToInt(a===0 || (a!==0 && b!==0));
case '=':
//return boolToInt((a===0 && b===0) || (a!==0 && b!==0));
return boolToInt(a===b);
case '~':
case '!':
return boolToInt(b===0);
}
return 0;
}
function evaluate(expression){
checkValidEx(expression);
var tokens = expression;
// Stack for numbers: 'values'
var values = [];
// Stack for Operators: 'ops'
var ops = [];
var i;
for (i = 0; i < tokens.length; i++){
// Current token is a whitespace, skip it
/*jslint continue:true*/
if (tokens.charAt(i) === ' '){
continue;
}
//echo(tokens.charAt(i));
// Current token is a number, push it to stack for numbers
if(isNumericString(tokens.charAt(i))){
var tempstring = '';
// There may be more than one digits in number
while(isNumericString(tokens.charAt(i))){
tempstring += tokens.charAt(i);
i++;
}
i--;
values.push(parseInt(tempstring, 10));
}
// Current token is an opening brace, push it to 'ops'
else if (tokens.charAt(i) === '('){
ops.push(tokens.charAt(i));
}
// Closing brace encountered, solve entire brace
else if (tokens.charAt(i) === ')'){
while (ops.peek() !== '('){
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
ops.pop();
}
// Current token is an operator.
else if (isOpToken(tokens.charAt(i))){
if(tokens.charAt(i)==='~' || tokens.charAt(i)==='!'){
//Push a dummy value onto the value stack so that it can be popped when the op is applied
values.push(0);
}
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.empty() && hasPrecedence(tokens.charAt(i), ops.peek())){
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
// Push current token to 'ops'.
ops.push(tokens.charAt(i));
}else if(isLetterChar(tokens.charAt(i))){
values.push(varLookup(tokens.charAt(i)));
}
}
// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!ops.empty()){
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
// Top of 'values' contains result, return it
return values.pop();
}
function printEval(ex){
echo("------------------");
echo("Expression: " + ex);
var result = evaluate(ex);
echo("Result: " + result);
}
var ttdiv=' ';//Divider for the table
function ttPrintRow(varList, varValues, ex){
var i, varOutString="";
for(i=0; i<varList.length; i++){
setVar(varList[i], varValues[i]);
varOutString += varValues[i] + ttdiv;
}
var result = evaluate(ex);
echo(varOutString + '| ' + result);
}
function incVarValues(vv){
var i;
for(i=vv.length-1; i>=0; i--){
if(vv[i]===0){
vv[i]=1;
break;
}else{
vv[i]=0;
}
}
return vv;
}
function printTruthTable(ex){
checkValidEx(ex);
var varList = getListOfVars(ex);
var numVars = varList.length;
var numttRows = Math.pow(2, numVars);
var varValues = [];
var headerRowOut = "";
var divRowOut = "";
var i;
for(i=0; i<numVars; i++){
varValues.push(0);
headerRowOut += varList[i] + ttdiv;
divRowOut += '-' + ttdiv;
}
echo('');
echo('Expression: ' + ex);
echo('');
echo(headerRowOut + '| Result');
echo(divRowOut + '| -');
for(i=0; i<numttRows; i++){
ttPrintRow(varList, varValues, ex);
varValues=incVarValues(varValues);
}
echo('');
resetVarStore();
}
function auto(ex){
checkValidEx(ex);
var containsVars = false;
var i;
for(i=0; i<ex.length; i++){
var c = ex.charAt(i);
if(isLetterChar(c) && c!=='T' && c!=='F'){
containsVars = true;
break;
}
}
if(containsVars){
printTruthTable(ex);
}else{
var result = evaluate(ex);
echo(result);
return result;
}
return true;
}
/*jslint nomen: true*/
return {
evaluate: evaluate,
printTruthTable: printTruthTable,
auto: auto,
isValidEx: isValidEx,
overrideEchoFunction: overrideEchoFunction,
vars: {
set: setVar,
get: varLookup,
getAll: getVarStore,
echoAll: printVarStore,
reset: resetVarStore
},
_private:{
incVarValues: incVarValues
}
};
}());
/*global process*/
/*global process:false*/
//For node.js scripts
if(process!==undefined && process && process.argv!==undefined){
solver.auto(process.argv[2]);
}