This is not an “ideal” answer, but you can solve it using several classes to conduct a logical connection / evaluation, and then recursively evaluate the circuit.
Create a base class, LogicalNode, and give it a list of inputs to control. Give it a base class function to evaluate all inputs and return output. This is overridden in derived classes. Each node type (INPUT, NOT, AND, OR) receives a derived class with a special overridden version of ComputOutput. If you are calculating the output of the node output, it should recursively process the tree, calculating all the inputs of the inputs, etc., until it reaches the "INPUT" nodes, which are fixed / logical system inputs.
You can quickly create new types (see code). There are not many comments here, but this should be somewhat explanatory.
Something like this (in C #):
public class LogicalNode { private List<LogicalNode> _inputs = new List<LogicalNode>(); private String _name = "Not Set"; public override string ToString() { return String.Format("Node {0}", _name); } public void Reset() { _inputs.Clear(); } public void SetName(String name) { _name = name; } protected List<LogicalNode> GetInputs() { return _inputs; } public void AddInput(LogicalNode node) { _inputs.Add(node); } protected virtual bool ComputeOutputInternal() { return false; } public bool ComputeOutput() {
And then (quickly) test it:
static void Main(string[] args) { // The test circuit // !((A&&B) || C) // ABC Out // 1 1 1 0 // 1 1 0 0 // 1 0 1 0 // 1 0 0 1 // 0 1 1 0 // 0 1 0 1 // 0 0 1 0 // 0 0 0 1 // // // /* ------- ------- * A - | | | | * | AND |-----| | ------- * B - | (D) | | | | | * ------- | OR |----| NOT |---- * | (E) | | (F) | * C --------------| | | | * ------- ------- */ LogicalInput A = new LogicalInput(); LogicalInput B = new LogicalInput(); LogicalInput C = new LogicalInput(); LogicalAND D = new LogicalAND(); LogicalOR E = new LogicalOR(); LogicalNOT F = new LogicalNOT(); A.SetName("A"); B.SetName("B"); C.SetName("C"); D.SetName("D"); E.SetName("E"); F.SetName("F"); D.AddInput(A); D.AddInput(B); E.AddInput(D); E.AddInput(C); F.AddInput(E); // Truth Table bool[] states = new bool[]{ true, false }; for(int idxA = 0; idxA < 2; idxA++) { for(int idxB = 0; idxB < 2; idxB++) { for(int idxC = 0; idxC < 2; idxC++) { A.SetState(states[idxA]); B.SetState(states[idxB]); C.SetState(states[idxC]); bool result = F.ComputeOutput(); Console.WriteLine("A = {0}, B = {1}, C = {2}, Output = {3}", A.GetState(), B.GetState(), C.GetState(), result.ToString()); } } } } }
With an exit:
A = True, B = True, C = True, Output = False A = True, B = True, C = False, Output = False A = True, B = False, C = True, Output = False A = True, B = False, C = False, Output = True A = False, B = True, C = True, Output = False A = False, B = True, C = False, Output = True A = False, B = False, C = True, Output = False A = False, B = False, C = False, Output = True
Was this helpful?