-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem4.js
72 lines (68 loc) · 1.76 KB
/
problem4.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
const variables = {};
const parseExpression = (expression) => {
expression = expression.replace(/\s/g, "");
const evaluate = (exp, startIndex) => {
let i = startIndex;
let result = false;
while (i < exp.length) {
switch (exp[i]) {
case "(":
result = evaluate(exp, i + 1);
i = result.endIndex + 1;
break;
case ")":
return {
result: result,
endIndex: i,
};
case "T":
result = true;
i++;
break;
case "F":
result = false;
i++;
break;
case "¬":
const nextEval = evaluate(exp, i + 1);
result = !nextEval.result;
i = nextEval.endIndex + 1;
break;
case "∧":
nextEval = evaluate(exp, i + 1);
result = result && nextEval.result;
i = nextEval.endIndex + 1;
break;
case "∨":
nextEval = evaluate(exp, i + 1);
result = result || nextEval.result;
i = nextEval.endIndex + 1;
break;
default:
if (variables.hasOwnProperty(exp[i])) {
result = variables[exp[i]];
i++;
} else {
throw new Error(`Unknown variable: ${exp[i]}`);
}
}
}
return {
result: result,
endIndex: exp.length,
};
};
return evaluate(expression, 0).result;
};
const evaluate = (input) => {
const tokens = input.split(" ");
if (tokens[0] === "let") {
if (tokens.length !== 4 || tokens[2] !== "=") {
throw new Error("Invalid assignment");
}
variables[tokens[1]] = tokens[3] === "T";
return `${tokens[1]}: ${tokens[3]}`;
} else {
return parseExpression(input) ? "T" : "F";
}
};