public List <Symbol> ConvertToPostfix(List <Symbol> list) { // This will be the final list of symbols List <Symbol> result = new List <Symbol>(); // This will be a temporary stack for operators Stack <Symbol> stack = new Stack <Symbol>(); foreach (Symbol t in list) { // Variable and Constant cant have children if (t is Variable || t is Constant) { result.Add(t); } else if (t is OpeningBracket) { stack.Push(t); } else if (t is ClosingBracket) { try { Symbol arrival = stack.Pop(); while (arrival is OpeningBracket == false) { result.Add(arrival); arrival = stack.Pop(); } } catch (InvalidOperationException) { throw new BracketsNotMatchingException(); } } else { while (stack.Count > 0) { if (t.Precedes(stack.Peek())) { break; } result.Add(stack.Pop()); } stack.Push(t); } } result.AddRange(stack.ToList()); return(result); }
public List <Symbol> Collect(string text) { List <Symbol> symbols = new List <Symbol>(); for (int i = 0; i < text.Length; ++i) { if (Char.IsWhiteSpace(text[i])) { continue; } Symbol v = null; Console.WriteLine(text[i] + " " + (int)text[i]); Symbol t = SymbolFactory.GetSymbol(text[i]); if (t == null) { t = SymbolFactory.GetSymbol(text, ref i); if (t == null) { throw new Exception("Could not produce a symbol from string starting at position " + (i + 1)); } } if (t is Quantifier) { ++i; v = SymbolFactory.GetSymbol(text, ref i); if (v == null) { throw new Exception("Invalid syntax after quantifier at position " + (i + 1)); } if (v is Variable == false) { throw new QuantifierRefersToConstantException(); } symbols.Add(v); } symbols.Add(t); } return(symbols); }
public void Simplify() { bool actionTaken; do { actionTaken = false; List <Symbol.Symbol> symbolList = Top.ReverseBFS(); foreach (var symbol in symbolList) { if (symbol is Operator) { Symbol.Symbol left = symbol.GetChildren()[0]; Symbol.Symbol right = symbol.GetChildren()[1]; if (left is Variable && right is Variable) { if (left.Name == right.Name) { if (symbol.Name == "AND" || symbol.Name == "OR" || symbol.Name == "IMPLIES") { actionTaken = true; Symbol.Symbol newSymbol = new Variable(name: left.Name); if (symbol.Parent == null) { Top = newSymbol; } else { symbol.Parent.SetChild(symbol.IndexInParent, newSymbol); } } } } } } } while (actionTaken); }