forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBooleanAlgebraGates.java
111 lines (101 loc) · 2.91 KB
/
BooleanAlgebraGates.java
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
package com.thealgorithms.bitmanipulation;
import java.util.List;
/**
* Implements various Boolean algebra gates (AND, OR, NOT, XOR, NAND, NOR)
*/
public final class BooleanAlgebraGates {
private BooleanAlgebraGates() {
// Prevent instantiation
}
/**
* Represents a Boolean gate that takes multiple inputs and returns a result.
*/
interface BooleanGate {
/**
* Evaluates the gate with the given inputs.
*
* @param inputs The input values for the gate.
* @return The result of the evaluation.
*/
boolean evaluate(List<Boolean> inputs);
}
/**
* AND Gate implementation.
* Returns true if all inputs are true; otherwise, false.
*/
static class ANDGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
for (boolean input : inputs) {
if (!input) {
return false;
}
}
return true;
}
}
/**
* OR Gate implementation.
* Returns true if at least one input is true; otherwise, false.
*/
static class ORGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
for (boolean input : inputs) {
if (input) {
return true;
}
}
return false;
}
}
/**
* NOT Gate implementation (Unary operation).
* Negates a single input value.
*/
static class NOTGate {
/**
* Evaluates the negation of the input.
*
* @param input The input value to be negated.
* @return The negated value.
*/
public boolean evaluate(boolean input) {
return !input;
}
}
/**
* XOR Gate implementation.
* Returns true if an odd number of inputs are true; otherwise, false.
*/
static class XORGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
boolean result = false;
for (boolean input : inputs) {
result ^= input;
}
return result;
}
}
/**
* NAND Gate implementation.
* Returns true if at least one input is false; otherwise, false.
*/
static class NANDGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
return !new ANDGate().evaluate(inputs); // Equivalent to negation of AND
}
}
/**
* NOR Gate implementation.
* Returns true if all inputs are false; otherwise, false.
*/
static class NORGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
return !new ORGate().evaluate(inputs); // Equivalent to negation of OR
}
}
}