-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtruth_table.ts
77 lines (62 loc) · 2.18 KB
/
truth_table.ts
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
import { Table, Input } from 'https://deno.land/x/[email protected]/mod.ts';
import { evaluate, preprocessExpression } from './propositional_logic.ts';
function generateTruthTable(expressions: string[]): string[][] {
const result: string[][] = [];
// preprocess expressions
expressions.forEach((expression, index) => {
expressions[index] = preprocessExpression(expression);
});
const variables = new Set<string>();
const values = new Map<string, boolean>();
// initialize variables
for (const expression of expressions) {
for (const char of expression) {
if (/[a-z]/i.test(char)) {
variables.add(char);
}
}
}
const variableArray = [...variables].sort((a, b) => -a.localeCompare(b));
// add variable to expressions if it is not present
for (const variable of variableArray) {
if (!expressions.includes(variable)) {
// insert the variable at the beginning of the expression
expressions = [variable, ...expressions];
}
}
// generate truth table header
result.push(
expressions.map(expression =>
expression
.replaceAll('∧', ' ∧ ')
.replaceAll('∨', ' ∨ ')
.replaceAll('→', ' → ')
.replaceAll('≡', ' ≡ ')
)
);
// generate truth table body
for (let i = 0; i < 2 ** variableArray.length; i++) {
for (let j = 0; j < variableArray.length; j++) {
values.set(variableArray[j], (i >> j) % 2 === 1);
}
const row = [];
for (const expression of expressions) {
row.push(evaluate(expression, values).toString());
}
result.push(row);
}
return result;
}
// Command line interface
console.log(`
Type expressions, separated by , or ;, or press enter to quit:
`);
let line: string | null = null;
while ((line = await Input.prompt({ message: '', prefix: '' }))) {
const expressions = line.split(/[;,]/).map(expression => expression.trim());
try {
new Table(...generateTruthTable(expressions)).border(true).render();
} catch (e) {
console.log(e);
}
}