Skip to content

Instantly share code, notes, and snippets.

@davebren
Created November 25, 2014 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davebren/0c17d024274750b1bf20 to your computer and use it in GitHub Desktop.
Save davebren/0c17d024274750b1bf20 to your computer and use it in GitHub Desktop.
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));
}
}
@thaiviet1994
Copy link

Creating a “truth table” is not hard, you can use an useful tool (CKod, at http://ckod.sourceforge.net/_/) to make a “truth table”.

  1. CKod homepage: http://ckod.sourceforge.net/
  2. CKod online: http://ckod.sourceforge.net/_/
  3. CKod forum: http://ckod.sourceforge.net/~/

Good luck to you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment