Created
November 25, 2014 15:58
-
-
Save davebren/0c17d024274750b1bf20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class TruthTable { | |
boolean[] variables; | |
private List<Boolean> rows; | |
private int numRows; | |
public TruthTable() { | |
init(getNumVariables()); | |
} | |
private TruthTable init(int numVariables) { | |
variables = new boolean[numVariables]; | |
numRows = ((int)Math.pow(2, variables.length)); | |
rows = new ArrayList<Boolean>(numRows); | |
return this; | |
} | |
public TruthTable compute() { | |
rows.clear(); | |
for (int i=0; i < numRows; i++) { | |
for (int j=variables.length -1; j >= 0; j--) { | |
variables[j] = (i / (int)Math.pow(2, j)) % 2 == 0; | |
} | |
boolean rowOutput = expression(); | |
rows.add(rowOutput); | |
} | |
return this; | |
} | |
public boolean equals(Object other) { | |
if (numRows != ((TruthTable)other).numRows) return false; | |
compute(); | |
((TruthTable)other).compute(); | |
for (int i=0; i < rows.size(); i++) { | |
if (rows.get(i) != ((TruthTable)other).rows.get(i)) return false; | |
} | |
return true; | |
} | |
public abstract int getNumVariables(); | |
public abstract boolean expression(); | |
public static void main(String[] args) { | |
TruthTable t1 = new TruthTable() { | |
public int getNumVariables() { | |
return 2; | |
} | |
public boolean expression() { | |
return !(variables[0] && variables[1]); | |
} | |
}; | |
TruthTable t2 = new TruthTable() { | |
public int getNumVariables() { | |
return 2; | |
} | |
public boolean expression() { | |
return (!variables[0] || !variables[1]); | |
} | |
}; | |
System.out.println(t1.equals(t2)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Creating a “truth table” is not hard, you can use an useful tool (CKod, at http://ckod.sourceforge.net/_/) to make a “truth table”.
Good luck to you!