-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKBDriver.java
More file actions
1102 lines (909 loc) · 32 KB
/
KBDriver.java
File metadata and controls
1102 lines (909 loc) · 32 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Author: Jackson Mishuk
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Scanner;
public class KBDriver {
public static void main(String[] args) {
Problem P;
if(args.length != 0) {
P = new Problem(args[0]);
if(!P.loadFile()) {
System.out.println("The File is not valid!");
return;
}
try (BufferedReader br = new BufferedReader(new FileReader(P.filePath))){
String line = br.readLine();
while(line != null) {
if(line.length() == 0 || line.charAt(0)=='#') {
line = br.readLine();
continue;
}
System.out.println("> " + line);
checkCmd(line, P);
line = br.readLine();
}
}catch(Exception e) {
e.printStackTrace();
}
}else {
P = new Problem();
Scanner s = new Scanner(System.in);
System.out.println("Welcome to the Knowledge Base!\n"
+ "Please TELL or ASK me anything!\n"
+ "(type HELP for more information)");
while(true) {
System.out.print("> ");
String input = s.nextLine();
if(!checkCmd(input, P)) {
break;
}
}
return;
}
}
/*
* This method is used to check an inputed argument
*
* Parameter(s): String(input), Problem(P)
*
* Returns: Boolean of success or failure
*/
private static boolean checkCmd(String input, Problem P) {
String firstArg="";
String secondArg="";
int firstSpaceIndex = input.indexOf(" ");
if(firstSpaceIndex != -1) {
firstArg = input.substring(0, firstSpaceIndex).toUpperCase();
secondArg = input.substring(firstSpaceIndex+1);
}else
firstArg = input.toUpperCase();
if(firstArg.equals("HELP"))
System.out.println(helpString());
else if(firstArg.equals("PRINT"))
System.out.print(argsString(P));
else if(firstArg.equals("TELLC")) {
Problem.Clause newClause = tellc(secondArg, P);
if(newClause!=null) {
for(Problem.Clause element:P.clauseList) {
if(element.hasSameLiterals(newClause))
return true;
}
P.clauseList.add(newClause);
}
}else if(firstArg.equals("ASK")) {
if(resolution(P.clauseList, secondArg, P)!=null) System.out.println("Yes, KB entails " + secondArg);
else System.out.println("No, KB does not entail " + secondArg);
}
else if(firstArg.equals("PROOF")) {
Problem.Clause finalClause = resolution(P.clauseList, secondArg, P);
if(finalClause!=null) {
System.out.println("Proof:\n" + getProof(finalClause));
}
else System.out.println("No proof exists");
}else if(firstArg.equals("PARSE"))
new ParseTree(secondArg, true/*parse print*/);
else if(firstArg.equals("CNF")) {
ParseTree Tree = new ParseTree(secondArg, false/*parse print*/);
Tree.convertToCnfForm();
System.out.println(Tree.toStr());
}
else if(firstArg.equals("TELL")) {
ParseTree Tree = new ParseTree(secondArg, false/*parse print*/);
Tree.convertToCnfForm();
String[] clauseArr = Tree.getClauses();
for(String element:clauseArr) {
Problem.Clause newClause = tellc(element, P);
P.clauseList.add(newClause);
}
}
else if(firstArg.equals("DONE") || firstArg.equals("EXIT") || firstArg.equals("QUIT")) {
System.out.println("Thank you for using the Knowledge Base!");
return false;
}
else
System.out.println("That command is not supported!");
return true;
}
/*
* Called when the HELP command is used
*
* Parameter(s): none
*
* Returns: String(List of all supported commands)
*/
private static String helpString() {
String ret = "\nSUPPORTED COMMANDS:\n\n";
ret += "\tHELP : Prints this help message\n";
ret += "\tDONE/EXIT/QUIT : Terminates the session\n";
ret += "\tTELLC <clause> : Adds the given <clause> to \n";
ret += "\tPRINT : Prints the clauses currently in \n";
ret += "\tASK <query> : Determines if the KB entails <query>.\n";
ret += "\tPROOF <query> : Prints a proof of <query> from \n";
ret += "\tPARSE <sentence>: Prints the parse tree of the given <sentence>.\n";
ret += "\tCNF <sentence> : Prints <sentence> in conjunctive normal form.\n";
ret += "\tTELL <sentence> : Adds the clauses in the CNF representation of <sentence> to \n";
return ret;
}
/*
* Called when the PRINT command is used
*
* Parameter(s): Problem
*
* Returns: String(All given clauses)
*/
private static String argsString(Problem P) {
String ret = "";
for(int i = 0; i<P.clauseList.size(); i++)
ret += "("+P.clauseList.get(i).toStr()+")" + "\n";
return ret;
}
/*
* Called when the TELLC command is used
*
* Parameter(s): String(clause), Problem
*
* Returns: boolean
*/
private static Problem.Clause tellc(String clauseStr, Problem P){
Problem.Clause newClause = new Problem.Clause(clauseStr, P);
return newClause;
}
static HashMap<Problem.Clause, Integer> map = new HashMap<Problem.Clause, Integer>();
/*
* Receives an empty Clause after doing an ask and gets the steps to the array, orders them, and returns the String
*
* Parameter(s): Clause(clause);
*
* Returns: String(of the proof)
*/
private static String getProof(Problem.Clause clause) {
String retStr = "";
ArrayList<Problem.Clause> proofArr = new ArrayList<Problem.Clause>();
proofArr = getParentClauses(clause, proofArr);
Collections.sort(proofArr, new Comparator<Problem.Clause>() {
public int compare(Problem.Clause clause1, Problem.Clause clause2) {
if(clause1.createdBy1 == null && !clause1.negatedGoal) {
if(clause2.createdBy1 == null && !clause2.negatedGoal)return 0;
else return -1;
}
if(clause2.createdBy1 == null && !clause2.negatedGoal) return 1;
if(clause1.createdBy1 != null) {
if(clause2.createdBy1 != null)return 0;
else return 1;
}
if(clause2.createdBy1 != null)return -1;
return 0;
}
});
Problem.Clause element = null;
for(int i = 0; i<proofArr.size(); i++) {
element = proofArr.get(i);
retStr += String.format(" %-3s %s", String.valueOf(i+1)+".", element.getProofStr(map));
map.put(element, i+1);
}
return retStr;
}
/*
* Receives an empty Clause after doing an ask and gets the Clauses that lead to the creation of the empty Clause
*
* Parameter(s): Clause(clause), ArrayList<Clause>(proofArr)
*
* Returns: ArrayList<Clause>(parents of inputed Clause)
*/
private static ArrayList<Problem.Clause> getParentClauses(Problem.Clause clause, ArrayList<Problem.Clause> proofArr){
if(clause == null) return proofArr;
getParentClauses(clause.createdBy1, proofArr);
getParentClauses(clause.createdBy2, proofArr);
for(Problem.Clause cElement: proofArr) {
if(clause.hasSameLiterals(cElement)) {
proofArr.remove(cElement);
break;
}
}
proofArr.add(clause);
return proofArr;
}
/*
* Receives a list of Clauses and a goal Clause and attempts to prove that the list entails the goal
*
* Parameter(s): ArrayList<Clause>(knowledgeBase), String(alpha), Problem(P)
*
* Returns: Clause(The empty Clause at the end if it is entailed or null if it is not)
*/
private static Problem.Clause resolution(ArrayList<Problem.Clause> knowledgeBase, String alpha, Problem P) {
ArrayList<Problem.Clause> clauses = new ArrayList<Problem.Clause>(P.clauseList);
ParseTree Tree = new ParseTree("~("+alpha+")", false/*parse print*/);
Tree.convertToCnfForm();
String[] strNegatedGoal = Tree.getClauses();
for(String strElement:strNegatedGoal) {
Problem.Clause tempClause = tellc(strElement, P);
tempClause.negatedGoal = true;
clauses.add(0, tempClause);
}
ArrayList<Problem.Clause> newClauses = new ArrayList<Problem.Clause>();
while(true) {
for(int i = 0; i<clauses.size(); i++) {
for(int j = i+1; j<clauses.size(); j++) {
ArrayList<Problem.Clause> resolvents = resolve(clauses.get(i), clauses.get(j), P);
for(Problem.Clause element:resolvents) {
if(element.emptyClause)
return element;
newClauses.addAll(resolvents);
}
}
}
int clausesSize = clauses.size();
int i = 0;
for(; i<newClauses.size(); i++) {
Problem.Clause newElement = newClauses.get(i);
int j = 0;
for(; j<clausesSize; j++) {
if(newElement.hasSameLiterals(clauses.get(j))) {
j = clausesSize;
continue;
}
if(j+1==clauses.size())
clauses.add(newElement);
}
}
if(clausesSize == clauses.size())return null;
}
}
/*
* Returns a list of Clauses that can be created with the two input Clauses
*
* Parameter(s): Clause(clauseI), Clause(clauseJ), Problem(P)
*
* Returns: ArrayList<Clause>(list of clauses entailed by clauseI & clauseJ)
*/
private static ArrayList<Problem.Clause> resolve(Problem.Clause clauseI, Problem.Clause clauseJ, Problem P){
ArrayList<Problem.Clause> retList = new ArrayList<Problem.Clause>();
Problem.Clause.Literal[] clauseIArr = clauseI.Literals.toArray(new Problem.Clause.Literal[0]);
Problem.Clause.Literal[] clauseJArr = clauseJ.Literals.toArray(new Problem.Clause.Literal[0]);
for(int i = 0; i < clauseIArr.length; i++) {
for(int j = 0; j < clauseJArr.length; j++) {
if(clauseIArr[i].Symbol.equals(clauseJArr[j].Symbol) && clauseIArr[i].negated != clauseJArr[j].negated) {
Problem.Clause Clause = new Problem.Clause(clauseI, clauseIArr, i, clauseJ, clauseJArr, j, P);
if(Clause.Literals.isEmpty())
Clause.emptyClause = true;
retList.add(Clause);
}
}
}
return retList;
}
/*
* The Problem class is used to hold information about the current run of the code
*
* Attributes: String filePath, ArrayList<Literal> literalList, ArrayList<Clause> clauseList, LinkedList<String> fileArgList
*
* Constructors: Problem(), Problem(String f)
*
* Methods: loadFile()
*
* *Contains Class Clause*
*/
private static class Problem{
//String representation of the path to the file
private String filePath = null;
//Array List of all clauses that have been created
private ArrayList<Clause> clauseList = new ArrayList<Clause>();
//Only created when the cmd argument is given a file
//Holds a LinkedList of all of the string(arguments) that were made within the file
private LinkedList<String> fileArgList = new LinkedList<String>();
//Used to create a Problem for interactive mode
Problem(){}
//Used to create a Problem for file mode
Problem(String f){
filePath = f;
}
//Used to read information from the file and adds each individual arg to the fileArgList object
private boolean loadFile() {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))){
String line = br.readLine();
while(line != null) {
this.fileArgList.add(line);
line = br.readLine();
}
} catch (Exception e) {return false;}
return true;
}
/*
* The Clause Class is for clauses which are literals(Symbols/negated symbols) with only or(v) connectives
*
* Attributes: PriorityQueue<Literal> Literals(Ordered in Lexicographical order), boolean emptyClause, boolean negatedGoal,
* Clause createdBy1, Clause createdBy2, LinkedList<Clause> created, String literalRemoved
*
* Constructors: Clause(Clause clauseI, Literal[] set1, int i, Clause clauseJ, Literal[] set2, int j, Problem P),
* Clause(String s, Problem P)
*
* Methods: hasSameLiterals(Clause): Checks to see if a Clause has the same set of literals that this Clause has,
* toStr(): Returns the String representation of the clause,
* getProofStr(HashMap<Clause, Integer>): Returns the line of a proof represented by the clause
*
* *Contains Class Literal*
*/
static private class Clause{
//Holds a list of the Literals of the clause(these statements must be ored together due to the definition of a clause in PL)
private PriorityQueue<Literal> Literals = new PriorityQueue<Literal>(new Comparator<Literal>() {
public int compare(Literal i1,Literal i2){
String s1 = i1.Symbol;
String s2 = i2.Symbol;
return s1.compareTo(s2);
}
});
//These variables are used for refutation method clauses only
//If it is the final state proving a contradiction in a refutation method
private boolean emptyClause = false;
//If created from the inverse of a goal state within the refutation method
private boolean negatedGoal = false;
//The clauses that entail this created clause
private Clause createdBy1 = null;
private Clause createdBy2 = null;
//When the clause is created through resolution of two clauses, this is the Symbol that is "Cancelled"
private String literalRemoved = "";
/*
* This constructor should only be called when dealing with Resolution
*
* It combines the literals from both sets excluding the index i for set 1 and index j for set 2
*/
Clause(Clause clauseI, Literal[] set1, int i, Clause clauseJ, Literal[] set2, int j, Problem P){
for(int k = 0; k <set1.length; k++) {
if(k != i)
Literals.add(set1[k]);
}
for(int k = 0; k <set2.length; k++) {
if(k != j && !Literals.contains(set2[k])) //to deal with repeats
Literals.add(set2[k]);
}
for(Clause cElement:P.clauseList) {
if(hasSameLiterals(cElement)) cElement = this;
}
createdBy1 = clauseI;
createdBy2 = clauseJ;
literalRemoved = set1[i].Symbol;
}
/*
* This is the standard constructor for clauses using a string representation of a clause
*/
Clause(String s, Problem P){
String[] literalArr = s.split("v");
StringBuilder substrElement;
for(String element:literalArr) {
boolean alreadyCreated = false;
boolean negated = false;
int negationIndex = element.indexOf("~");
if(negationIndex != -1) {
negated = true;
substrElement = new StringBuilder(element.substring(negationIndex+1));
}else
substrElement = new StringBuilder(element);
for(int i = 0; i<substrElement.length(); i++) {
if(substrElement.charAt(i) == ' ') { substrElement.deleteCharAt(i); i--;}
}
Literals.add(new Literal(substrElement.toString(), negated));
}
}
/*
* Checks to see if a Clause has the same set of literals that this Clause has
*
* Parameter(s): Clause(element)
*
* Returns: Boolean(True if same, false if not)
*/
private boolean hasSameLiterals(Clause element) {
if(element.Literals.size() != this.Literals.size())return false;
PriorityQueue<Literal> thisLiteralClone = new PriorityQueue<Literal>(this.Literals);
PriorityQueue<Literal> literalsClone = new PriorityQueue<Literal>(element.Literals);
while(literalsClone.peek()!=null) {
Literal thisLiteral = thisLiteralClone.poll();
Literal literal = literalsClone.poll();
if(!literal.Symbol.equals(thisLiteral.Symbol) || literal.negated != thisLiteral.negated) {
return false;
}
}
return true;
}
/*
* Returns the String representation of the clause
*
* Parameter(s): None
*
* Returns: String
*/
private String toStr(){
String retStr = "";
PriorityQueue<Literal> literalsCopy = new PriorityQueue<Literal>(Literals);//This array is not in particular order. Need to find a new way.//This array is not in particular order. Need to find a new way.
if(literalsCopy.peek()!=null) {
Literal element = literalsCopy.poll();
retStr += element.toStr();
while(literalsCopy.peek() != null) {
element = literalsCopy.poll();
retStr += " v ";
retStr += element.toStr();
}
}else return "()";
return retStr;
}
/*
* Returns the line of a proof represented by the clause
*
* Parameter(s): HashMap<Problem.Clause, Integer>(map)
*
* Returns: Boolean(True if same, false if not)
*/
private String getProofStr(HashMap<Problem.Clause, Integer> map) {
if(createdBy1 == null) {
if(negatedGoal)
return String.format("%-30s[Negated Goal]\n", toStr());
return String.format("%-30s[Premise]\n", toStr());
}
return String.format("%-30s[Resolution on %s: %d, %d]\n", toStr(), literalRemoved, map.get(createdBy1), map.get(createdBy2));
}
/*
* The Literal Class is used to store the Symbol and to allow the database to store if that Symbol is negated
*
* Attributes: String Symbol; boolean negated
*
* Constructor: Literal(String s, boolean n, Problem P)
*
* Method: toStr(): Returns the String representation of the Literal
*/
static private class Literal{
String Symbol;
boolean negated;
//Used to create a Literal with Symbol s with negation n
Literal(String s, boolean n) {
Symbol = s;
negated = n;
}
//Returns the String representation of the Literal
private String toStr() {
String retStr = "";
if(this.negated)
retStr += "~";
retStr += this.Symbol;
return retStr;
}
}
}
}
/*
* The ParseTree Class is used to apply an order of operations to Propositional Logic
*
* Attributes: Node root, static boolean parsePrint, boolean unarySentance
*
* Constructor: makeParseTree(String arg, int distRoot)
*
* Method: getClauses(): , toTreeString(Node), convertToCnfForm(), convertToCnfForm(Node), toStr(), toStr(Node, String)
*
* *Contains Class Node*
*/
private static class ParseTree{
//The root is the Node in the tree that has no parents. In other words, all Nodes in the ParseTree are direct decendents of this Node
private Node root = null;
//This is true only when a ParseTree is created from the Parse command and prints out the parsing steps as it expands a string
private static boolean parsePrint;
//Used for toString() when the sentence consists of only 1 clause
private boolean unarySentance = true;
//This constructor is used to make a Parse Tree from String arg
ParseTree(String arg, boolean pp){
parsePrint = pp;
arg = arg.replace(" ", "");
if(parsePrint) System.out.print("Orig: ");
root = makeParseTree(arg, 0);
}
/*
* PRE: Should only be called with an argument without any spaces. Call through constructor
*
* Called from the constructor to make a parseTree
*
* Parameter(s): String(arg), int(distRoot)
*
* Returns: Node(Root node of parse tree
*/
private static Node makeParseTree(String arg, int distRoot) {
Node retNode = null;
int openParensCount = 0;
for(int index = 0; index<arg.length(); index++) {
char element = arg.charAt(index);
if(element == '(') {
openParensCount++;
continue;
}
if(element ==')') {
openParensCount--;
continue;
}
if(openParensCount == 0) {
//Used to deal withif and only if(<=>) connective
if(element == '<' && arg.charAt(index+1) == '=' && arg.charAt(index+2) == '>') {
retNode = new Node("<=>");
//Printing for parse command call
if(parsePrint) {
System.out.printf("[%s] Binary [<=>]\n", arg);
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("LHS: ");
}
retNode.addLeft(makeParseTree(arg.substring(0, index), distRoot+1));
//Printing for parse command call
if(parsePrint) {
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("RHS: ");
}
retNode.addRight(makeParseTree(arg.substring(index+3), distRoot+1));
return retNode;
}
//Used to deal with implies(=>) connective
if(element == '=' && arg.charAt(index+1) == '>') {
retNode = new Node("=>");
//Printing for parse command call
if(parsePrint) {
System.out.printf("[%s] Binary [=>]\n", arg);
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("LHS: ");
}
retNode.addLeft(makeParseTree(arg.substring(0, index), distRoot+1));
//Printing for parse command call
if(parsePrint) {
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("RHS: ");
}
retNode.addRight(makeParseTree(arg.substring(index+2), distRoot+1));
return retNode;
}
//Used to deal with and(^) connective
if(element == '^') {
retNode = new Node("^");
//Printing for parse command call
if(parsePrint) {
System.out.printf("[%s] Binary [^]\n", arg);
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("LHS: ");
}
retNode.addLeft(makeParseTree(arg.substring(0, index), distRoot+1));
//Printing for parse command call
if(parsePrint) {
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("RHS: ");
}
retNode.addRight(makeParseTree(arg.substring(index+1), distRoot+1));
return retNode;
}
//Used to deal with or(v) connective
if(element == 'v') {
retNode = new Node("v");
//Printing for parse command call
if(parsePrint) {
System.out.printf("[%s] Binary [v]\n", arg);
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("LHS: ");
}
retNode.addLeft(makeParseTree(arg.substring(0, index), distRoot+1));
//Printing for parse command call
if(parsePrint) {
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("RHS: ");
}
retNode.addRight(makeParseTree(arg.substring(index+1), distRoot+1));
return retNode;
}
}
}
//Used to deal with negation(~)
if(arg.charAt(0) == '~') {
retNode = new Node("~");
//Printing for parse command call
if(parsePrint) {
System.out.printf("[%s] Unary [~]\n", arg);
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("Sub: ");
}
retNode.addRight(makeParseTree(arg.substring(1), distRoot+1));
return retNode;
}
//Used to deal with symbols
if(arg.charAt(0)!='(') {
//Printing for parse command call
if(parsePrint)
System.out.printf("[%s] Unary [symbol]: [%s]\n", arg, arg);
return new Node(arg);
}
//Used to deal with parenthesis
retNode = new Node("()");
//Printing for parse command call
if(parsePrint) {
System.out.printf("[%s] Unary [()]\n", arg);
for(int i = 0; i<=distRoot; i++)
System.out.print(" ");
System.out.print("Sub: ");
}
retNode.addRight(makeParseTree(arg.substring(1, arg.length()-1), distRoot+1));
return retNode;
}
/*
* PRE: Make sure that the tree has been reformatted to CNF format using convertToCnfForm() before using this method
*
* Used to parse clauses out of the CNF formatted tree
*
* Parameter(s): None
*
* Returns: String[](The String format of the list of Clauses)
*/
private String[] getClauses() {
String treeString = toTreeString(root);
String[] clauseArr = treeString.split("\\^");
return clauseArr;
}
/*
* Used to return all of the string forms of the nodes descending from r
*
* Parameter(s): Node(r)
*
* Returns: String(The String format of the ParseTree)
*/
private String toTreeString(Node r) {
if(r==null) return "";
String retStr = "";
retStr = toTreeString(r.left);
if(!r.value.equals("()"))retStr += r.value;
retStr += toTreeString(r.right);
return retStr;
}
/*
* Used to convert a ParseTree
*
* Parameter(s): None
*
* Returns: ParseTree(The converted ParseTree)
*/
private ParseTree convertToCnfForm() {
root = convertToCnfForm(root);
String tempStr = "";
String newTempStr = toTreeString(root);
while(!tempStr.equals(newTempStr)) {
tempStr = toTreeString(root);
root = convertToCnfForm(root);
newTempStr = toTreeString(root);
}
return this;
}
/*
* Used to convert a ParseTree
*
* Parameter(s): Node r
*
* Returns: Node(root of the converted ParseTree
*/
private Node convertToCnfForm(Node r) {
//If root is null then return without performing any actions
if (r==null) return null;
//Used to convert if and only if(a<=>b) to (a=>b)^(b=>a)
if(r.value.equals("<=>")) {
Node newRoot = new Node("^");
newRoot.left = new Node("()", newRoot);
newRoot.right = new Node("()", newRoot);
newRoot.left.right = new Node("=>", newRoot.left);
newRoot.right.right = new Node("=>",newRoot.right);
newRoot.left.right.addLeft(r.left);
newRoot.left.right.addRight(r.right);
newRoot.right.right.addLeft(r.right);
newRoot.right.right.addRight(r.left);
newRoot.parent = r.parent;
r = newRoot;
}
//Used to convert implies(a=>b) to (~a)v(b)
else if(r.value.equals("=>")) {
Node newRoot = new Node("v");
newRoot.left = new Node("~", newRoot);
newRoot.left.addRight(r.left);
newRoot.addRight(r.right);
newRoot.parent = r.parent;
r = newRoot;
r = convertToCnfForm(r);
return r;
}
//Used to push in negation
else if(r.value.equals("~")) {
//Used to find the next node on the right that is not a parentheses
Node elementRight = r.right;
while(elementRight.value.equals("()"))
elementRight = elementRight.right;
//Used to deal with double negation(~(~a)) to (a)
if(elementRight.value.equals("~")) {
elementRight.right.parent = r.parent;
r = elementRight.right;
//Used to deal with demorgan's(~(avb)) to (~a^~b)
}else if(elementRight.value.equals("v")) {
Node newRoot = new Node("^");
newRoot.left = new Node("~", newRoot);
newRoot.right = new Node("~", newRoot);
newRoot.left.addRight(elementRight.left);
newRoot.right.addRight(elementRight.right);
newRoot.parent = r.parent;
r = newRoot;
r = convertToCnfForm(r);
return r;
//Used to deal with demorgan's(~(a^b)) to (~av~b)
}else if(elementRight.value.equals("^")) {
Node newRoot = new Node("v");
newRoot.left = new Node("~", newRoot);
newRoot.right = new Node("~", newRoot);
newRoot.left.addRight(elementRight.left);
newRoot.right.addRight(elementRight.right);
newRoot.parent = r.parent;
r = newRoot;
r = convertToCnfForm(r);
return r;
}
}
//Used to deal with distributive(av(b^c)) or ((b^c)va) to ((avb)^(avc))
else if(r.value.equals("v")) {
//Used to find the next node on the right that is not a parentheses
Node elementRight = r.right;
while(elementRight.value.equals("()"))
elementRight = elementRight.right;
//Used to find the next node on the left that is not a parentheses
Node elementLeft = r.left;
while(elementLeft.value.equals("()"))
elementLeft = elementLeft.right;
//((b^c)va) to ((avb)^(avc))
if(elementLeft.value.equals("^")) {
Node newRoot = new Node("^");
//left of root
newRoot.left = new Node("v", newRoot);
newRoot.left.addLeft(r.right);
newRoot.left.addRight(elementLeft.left);
//right of root
newRoot.right = new Node("v", newRoot);
newRoot.right.addLeft(r.right);
newRoot.right.addRight(elementLeft.right);
r=newRoot;
//(av(b^c)) to ((avb)^(avc))
}else if(elementRight.value.equals("^")) {
Node newRoot = new Node("^");
//left of root
newRoot.left = new Node("v", newRoot);
newRoot.left.addLeft(r.left);
newRoot.left.addRight(elementRight.left);
//right of root
newRoot.right = new Node("v", newRoot);
newRoot.right.addLeft(r.left);
newRoot.right.addRight(elementRight.right);
r=newRoot;
}
}
//Used to remove parentheses
else if(r.value.equals("()")) {
r.right.parent = r.parent;
r = r.right;
r = convertToCnfForm(r);
return r;
}
r.left = convertToCnfForm(r.left);
r.right = convertToCnfForm(r.right);
return r;
}
/*
* PRE: Call this on a ParseTree once it has been converted to CNF form. Call convertToCnfForm() before calling this method
*
* Returns the String representation of the sentence(CNF form)
*
* Parameter(s): None
*
* Returns: String
*/
private String toStr() {
String retStr = "";
retStr = toStr(root, retStr);
if(unarySentance)
retStr = "("+retStr+")";
return "Result: " + retStr;
}
/*
* PRE: Should be called through toStr()
*
* Returns the String representation of the nodes descending from root n
*
* Parameter(s): Node n, String retStr
*