001 /* 002 * Created on May 3, 2003 by Ravi Mohan 003 * 004 */ 005 package aima.util; 006 007 import java.util.ArrayList; 008 import java.util.Collections; 009 import java.util.HashSet; 010 import java.util.List; 011 import java.util.Set; 012 013 import aima.logic.fol.parsing.ast.Variable; 014 import aima.logic.propositional.parsing.ast.BinarySentence; 015 import aima.logic.propositional.parsing.ast.Sentence; 016 import aima.logic.propositional.parsing.ast.Symbol; 017 import aima.logic.propositional.parsing.ast.SymbolComparator; 018 import aima.logic.propositional.parsing.ast.UnarySentence; 019 020 /** 021 * @author Ravi Mohan 022 * 023 */ 024 025 public class LogicUtils { 026 027 public static Sentence chainWith(String connector, List sentences) { 028 if (sentences.size() == 0) { 029 return null; 030 } else if (sentences.size() == 1) { 031 return (Sentence) sentences.get(0); 032 } else { 033 Sentence soFar = (Sentence) sentences.get(0); 034 for (int i = 1; i < sentences.size(); i++) { 035 Sentence next = (Sentence) sentences.get(i); 036 soFar = new BinarySentence(connector, soFar, next); 037 } 038 return soFar; 039 } 040 } 041 042 public static Sentence reorderCNFTransform(Set<Symbol> positiveSymbols, 043 Set<Symbol> negativeSymbols) { 044 List<Symbol> plusList = new Converter<Symbol>() 045 .setToList(positiveSymbols); 046 List<Symbol> minusList = new Converter<Symbol>() 047 .setToList(negativeSymbols); 048 Collections.sort(plusList, new SymbolComparator()); 049 Collections.sort(minusList, new SymbolComparator()); 050 051 List<Sentence> sentences = new ArrayList<Sentence>(); 052 for (int i = 0; i < positiveSymbols.size(); i++) { 053 sentences.add(plusList.get(i)); 054 } 055 for (int i = 0; i < negativeSymbols.size(); i++) { 056 sentences.add(new UnarySentence(minusList.get(i))); 057 } 058 if (sentences.size() == 0) { 059 return new Symbol("EMPTY_CLAUSE"); // == empty clause 060 } else { 061 return LogicUtils.chainWith("OR", sentences); 062 } 063 } 064 065 public static Set<Variable> stringsToVariables(Set<String> strings) { 066 Set<Variable> vars = new HashSet<Variable>(); 067 for (String str : strings) { 068 vars.add(new Variable(str)); 069 } 070 return vars; 071 } 072 073 }