public string Ask(Symbol query, KnowledgeBase kb) { _kb = kb; _path = new List <string>(); if (kb.SymbolIsKnown(query)) { return("YES: " + query.Name); } if (BackwardChain(query)) { return("YES: " + PathString); } return("NO"); }
private bool BackwardChain(Symbol s) { _path.Insert(0, s.Name); if (_kb.SymbolIsKnown(s)) { return(true); } foreach (var symbol in GetSymbolsImplying(s)) { if (!BackwardChain(symbol)) { return(false); } } return(true); }
public string Ask(Symbol query, KnowledgeBase kb) { _kb = kb; // count = Dictionary<string, int> // Number of premises for each sentence var count = new Dictionary <Sentence, int>(); foreach (var sentence in kb.Knowledge) { count[sentence] = sentence.LeftSide.Count; } // inferred = Dictionary<string, bool> // Whether each symbol has been inferred yet var inferred = new Dictionary <string, bool>(); foreach (var symbol in kb.Symbols) { inferred[symbol.Key] = false; } // agenda = List<Symbol> // The inferred symbols. Begins with "known" symbols var agenda = new Stack <Symbol>(); foreach (var symbol in kb.Symbols) { if (kb.SymbolIsKnown(symbol.Value)) { agenda.Push(symbol.Value); } } string path = ""; foreach (var symbol in agenda) { path += symbol.Name + " "; } while (agenda.Count > 0) { var premise = agenda.Pop(); if (!inferred[premise.Name]) { inferred[premise.Name] = true; foreach (var sentence in GetSentencesContaining(premise)) { --count[sentence]; if (count[sentence] == 0) { if (sentence.Implication.Name == query.Name) { return("YES: " + path + query.Name); } agenda.Push(sentence.Implication); path += sentence.Implication.Name + " "; } } } } return(query.Name + ": NO"); }