Skip to content

Commit e5dae59

Browse files
committed
Add algo for BooleanGateslogic
1 parent 2338428 commit e5dae59

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import java.util.List;
4+
5+
/**
6+
* Implements various Boolean algebra gates (AND, OR, NOT, XOR, NAND, NOR)
7+
* using Java, generalized to handle multiple inputs.
8+
*/
9+
public final class BooleanAlgebraGates {
10+
11+
private BooleanAlgebraGates() {
12+
// Private constructor to prevent instantiation
13+
}
14+
15+
/**
16+
* Interface representing a Boolean gate that takes multiple inputs and returns a result.
17+
*/
18+
interface BooleanGate {
19+
boolean evaluate(List<Boolean> inputs);
20+
}
21+
22+
/**
23+
* AND Gate implementation.
24+
* Returns true if all inputs are true, otherwise false.
25+
*/
26+
static class ANDGate implements BooleanGate {
27+
@Override
28+
public boolean evaluate(List<Boolean> inputs) {
29+
for (boolean input : inputs) {
30+
if (!input) {
31+
return false;
32+
}
33+
}
34+
return true;
35+
}
36+
}
37+
38+
/**
39+
* OR Gate implementation.
40+
* Returns true if at least one input is true, otherwise false.
41+
*/
42+
static class ORGate implements BooleanGate {
43+
@Override
44+
public boolean evaluate(List<Boolean> inputs) {
45+
for (boolean input : inputs) {
46+
if (input) {
47+
return true;
48+
}
49+
}
50+
return false;
51+
}
52+
}
53+
54+
/**
55+
* NOT Gate implementation (Unary operation).
56+
* Only accepts a single input and returns the negation.
57+
*/
58+
static class NOTGate {
59+
/**
60+
* Evaluates the negation of a single input.
61+
*
62+
* @param input The input value to be negated.
63+
* @return The negation of the input.
64+
*/
65+
public boolean evaluate(boolean input) {
66+
return !input;
67+
}
68+
}
69+
70+
/**
71+
* XOR Gate implementation.
72+
* Returns true if an odd number of inputs are true, otherwise false.
73+
*/
74+
static class XORGate implements BooleanGate {
75+
@Override
76+
public boolean evaluate(List<Boolean> inputs) {
77+
boolean result = false;
78+
for (boolean input : inputs) {
79+
result ^= input;
80+
}
81+
return result;
82+
}
83+
}
84+
85+
/**
86+
* NAND Gate implementation.
87+
* Returns true if at least one input is false, otherwise false.
88+
*/
89+
static class NANDGate implements BooleanGate {
90+
@Override
91+
public boolean evaluate(List<Boolean> inputs) {
92+
return !new ANDGate().evaluate(inputs); // Equivalent to negation of AND
93+
}
94+
}
95+
96+
/**
97+
* NOR Gate implementation.
98+
* Returns true if all inputs are false, otherwise false.
99+
*/
100+
static class NORGate implements BooleanGate {
101+
@Override
102+
public boolean evaluate(List<Boolean> inputs) {
103+
return !new ORGate().evaluate(inputs); // Equivalent to negation of OR
104+
}
105+
}
106+
}

0 commit comments

Comments
 (0)