-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTruthTable.java
More file actions
57 lines (44 loc) · 1.54 KB
/
TruthTable.java
File metadata and controls
57 lines (44 loc) · 1.54 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
public class TruthTable {
public boolean[][] inputs;
public boolean[] outputs;
int numInputs;
public TruthTable(int numInputs) {
this.numInputs = numInputs;
inputs = new boolean[(int) Math.pow(2, numInputs)][numInputs];
outputs = new boolean[(int) Math.pow(2, numInputs)];
int count = (int) Math.pow(2, numInputs);
for (int i = 0; i < count; i++){
for (int j = 0; j < numInputs; j++){
int lengthOfCycle = count / (int) Math.pow(2, j);
int indexInCycle = i % lengthOfCycle;
inputs[i][j] = indexInCycle < lengthOfCycle/2;
}
}
}
public TruthTable(boolean[][] inputs, boolean[] outputs) {
this.inputs = inputs;
this.outputs = outputs;
this.numInputs = inputs[0].length;
}
public boolean calculate(boolean[] in) {
for (int i = 0; i < inputs.length; i++){
for (int j = 0; j < numInputs; j++){
if (inputs[i][j] != in[j]) break;
if (j == numInputs - 1) return outputs[i];
}
}
return false;
}
public String toString(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inputs.length; i++){
for (int j = 0; j < numInputs; j++){
sb.append(inputs[i][j] ? "T " : "F ");
}
sb.append("| ");
sb.append(outputs[i] ? "T" : "F");
sb.append("\n");
}
return sb.toString();
}
}