samples/apifest1/day2/pinbasedsolution/src/org/netbeans/apifest/boolcircuit/Element.java
1 package org.netbeans.apifest.boolcircuit;
4 * Representation of an element in the circuit.
5 * The internal behaviour of the element is opaque to the API user,
6 * it can only be used as a building block for logical equations,
7 * using primitive operation factories and a factory for input
9 * Elements are chained to create the logical net.
10 * The inputs to the net are represented by the elements created
11 * by {@link #createInput(boolean[])} factory method.
13 public abstract class Element {
15 /** Creates a new instance of Element */
21 abstract double evaluate(double[] inputs);
23 abstract int maxInput();
26 * Creates an Element representing 2-input AND function.
29 public static Element createAnd(
30 final Element source1, final Element source2
32 return new Element() {
33 double evaluate(double[] inputs) {
34 return source1.evaluate(inputs) * source2.evaluate(inputs);
38 return Math.max(source1.maxInput(), source2.maxInput());
44 * Creates an Element representing 2-input OR function.
47 public static Element createOr(
48 final Element source1, final Element source2
50 return new Element() {
51 double evaluate(double[] inputs) {
52 double x = source1.evaluate(inputs);
53 double y = source2.evaluate(inputs);
54 return 1 - (1 - x)*(1-y);
58 return Math.max(source1.maxInput(), source2.maxInput());
64 * Creates an Element representing negation.
67 public static Element createNot(final Element source1) {
68 return new Element() {
69 double evaluate(double[] inputs) {
70 return 1 - source1.evaluate(inputs);
74 return source1.maxInput();
80 * Creates an Element representing input to the logical net.
83 public static Element createInput(final int pin) {
84 return new Element() {
85 double evaluate(double[] inputs) {
95 // BEGIN: apifest.day2.pinbasedsolution.FunctionFactory
97 * Creates an Element with user-defined transfer function.
99 public static Element createGate(
100 final Element source1, final Element source2, final Function function
102 return new Element() {
103 double evaluate(double[] inputs) {
104 double x = source1.evaluate(inputs);
105 double y = source2.evaluate(inputs);
106 double result = function.evaluate(x, y);
107 if (result < 0.0 || result > 1.0) {
108 throw new InternalError("Illegal gate function");
114 return Math.max(source1.maxInput(), source2.maxInput());
118 // END: apifest.day2.pinbasedsolution.FunctionFactory