This is the syntax highlighted version of MultiwayAnd.java.
/*************************************************************************
* Compilation: javac MultiwayAnd.java
* Execution: java MultiwayAnd
*
* M-way AND gate. Build using divide-and-conquer.
*
*************************************************************************/
public class MultiwayAnd extends Circuit {
public MultiwayAnd(int N) {
super(N, 1);
// illegal cases
if (N <= 0) throw new RuntimeException("Illegal size of Multiway AND requested");
// base case
if (N == 1) this.inAt(0).solderTo(this.outAt(0));
// base case
else if (N == 2) {
Circuit and = new And();
this.inAt(0).solderTo(and.inAt(0));
this.inAt(1).solderTo(and.inAt(1));
and.outAt(0).solderTo(outAt(0));
}
else {
Circuit and = new And();
Circuit and0 = new MultiwayAnd(N/2);
Circuit and1 = new MultiwayAnd(N - N/2);
for (int i = 0; i < N/2; i++) this.inAt(i).solderTo(and0.inAt(i));
for (int i = N/2; i < N; i++) this.inAt(i).solderTo(and1.inAt(i-N/2));
and0.outAt(0).solderTo(and.inAt(0));
and1.outAt(0).solderTo(and.inAt(1));
and.outAt(0).solderTo(this.outAt(0));
}
}
/////////////////////////////////////////////////////////////////////////
// test client
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
Circuit and = new MultiwayAnd(N);
Light light = new Light();
Switch[] inputs = new Switch[N];
for (int i = 0; i < N; i++) {
inputs[i] = new Switch();
inputs[i].outAt(0).solderTo(and.inAt(i));
}
and.outAt(0).solderTo(light.inAt(0));
for (int i = 0; i < N; i++) {
inputs[i].turnOn();
}
inputs[0].turnOff();
System.out.println(light.isOn());
inputs[0].turnOn();
System.out.println(light.isOn());
}
}
Last updated: Fri May 21 16:54:24 EDT 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.