I have a list of logical expressions,
const expressions = [
'A&(B|C)',
'A|(B&C)',
'A|(B&(C|D))',
'A|(B&C&D)',
];
From these expressions, I am aiming to obtain the following output,
[[A, B], [A, C]]
[[A], [B, C]]
[A, [B, C], [B, D]]
[A, [B, C, D]]
I attempted to achieve this using the code below, however, I am receiving empty arrays instead of the correct result.
class ParsedExpression {
operator: string | null;
variables: string[];
subExpressions: ParsedExpression[];
constructor(operator: string | null, variables: string[], subExpressions: ParsedExpression[]) {
this.operator = operator;
this.variables = variables;
this.subExpressions = subExpressions;
}
}
function parseExpression(expression: string): ParsedExpression {
const stack: ParsedExpression[] = [];
let currentExpr: ParsedExpression | null = null;
let currentVariable = '';
for (const char of expression) {
if (char === '(') {
if (currentExpr !== null) {
stack.push(currentExpr);
}
currentExpr = null;
} else if (char === ')') {
if (stack.length > 0) {
const prevExpr = stack.pop();
if (prevExpr !== null && currentExpr !== null) {
prevExpr.subExpressions.push(currentExpr);
currentExpr = prevExpr;
}
}
} else if (char === '&' || char === '|') {
if (currentExpr === null) {
currentExpr = new ParsedExpression(char, [], []);
} else {
currentExpr.operator = char;
}
} else {
if (currentExpr === null) {
currentExpr = new ParsedExpression(null, [], []);
}
currentExpr.variables.push(char);
}
}
return currentExpr as ParsedExpression;
}
function generateCombinations(parsedExpr: ParsedExpression): string[][] {
if (!parsedExpr.operator) {
return [parsedExpr.variables];
}
const leftCombinations = parsedExpr.subExpressions.length > 0 ? generateCombinations(parsedExpr.subExpressions[0]) : [[]];
const rightCombinations = parsedExpr.subExpressions.length > 1 ? generateCombinations(parsedExpr.subExpressions[1]) : [[]];
const combinations: string[][] = [];
for (const left of leftCombinations) {
for (const right of rightCombinations) {
combinations.push(left.concat(right));
}
}
return combinations;
}
const expressions = [
'A&(B|C)',
'A|(B&C)',
'A|(B&(C|D))',
'A|(B&C&D)',
];
for (const expr of expressions) {
const parsedExpression = parseExpression(expr);
const combinations = generateCombinations(parsedExpression);
console.log(`Expression: ${expr}`);
console.log(`Combinations: ${JSON.stringify(combinations)}`);
console.log('-------------------');
}
The current output shows empty combinations for each expression. Is there any way to fix this and get the desired combinations?