samples/apifest1/day2/pinbasedsolution/src/org/netbeans/apifest/boolcircuit/Element.java
4 * Created on 12. Ĩervenec 2006, 14:14
6 * To change this template, choose Tools | Template Manager
7 * and open the template in the editor.
10 package org.netbeans.apifest.boolcircuit;
13 * Representation of an element in the circuit.
14 * The internal behaviour of the element is opaque to the API user, it can only
15 * be used as a building block for logical equations, using primitive operation
16 * factories and a factory for input pin representation.
17 * Elements are chained to create the logical net. The inputs to the net are
18 * represented by the elements created by {@link #createInput(boolean[])}
21 public abstract class Element {
23 /** Creates a new instance of Element */
29 abstract double evaluate(double[] inputs);
31 abstract int maxInput();
34 * Creates an Element representing 2-input AND function.
37 public static Element createAnd(final Element source1, final Element source2) {
38 return new Element() {
39 double evaluate(double[] inputs) {
40 return source1.evaluate(inputs) * source2.evaluate(inputs);
44 return Math.max(source1.maxInput(), source2.maxInput());
50 * Creates an Element representing 2-input OR function.
53 public static Element createOr(final Element source1, final Element source2) {
54 return new Element() {
55 double evaluate(double[] inputs) {
56 double x = source1.evaluate(inputs);
57 double y = source2.evaluate(inputs);
58 return 1 - (1 - x)*(1-y);
62 return Math.max(source1.maxInput(), source2.maxInput());
68 * Creates an Element representing negation.
71 public static Element createNot(final Element source1) {
72 return new Element() {
73 double evaluate(double[] inputs) {
74 return 1 - source1.evaluate(inputs);
78 return source1.maxInput();
84 * Creates an Element representing input to the logical net.
87 public static Element createInput(final int pin) {
88 return new Element() {
89 double evaluate(double[] inputs) {
99 // BEGIN: apifest.day2.pinbasedsolution.FunctionFactory
101 * Creates an Element with user-defined transfer function.
103 public static Element createGate(final Element source1, final Element source2, final Function function) {
104 return new Element() {
105 double evaluate(double[] inputs) {
106 double x = source1.evaluate(inputs);
107 double y = source2.evaluate(inputs);
108 double result = function.evaluate(x, y);
109 if (result < 0.0 || result > 1.0) throw new InternalError("Illegal gate function");
114 return Math.max(source1.maxInput(), source2.maxInput());
118 // END: apifest.day2.pinbasedsolution.FunctionFactory