samples/composition/src-api2.0-compat/org/apidesign/math/Arithmetica.java
changeset 321 06bf3a32eaa0
parent 210 acf2c31e22d4
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/samples/composition/src-api2.0-compat/org/apidesign/math/Arithmetica.java	Sat Feb 14 17:30:06 2009 +0100
     1.3 @@ -0,0 +1,61 @@
     1.4 +package org.apidesign.math;
     1.5 +
     1.6 +/** Class to simplify arithmetical operations, improved version to compute
     1.7 + * the sum for ranges, but only if one uses the new constructor to indicate
     1.8 + * need for new version.
     1.9 + *
    1.10 + * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.11 + * @version 2.0
    1.12 + */
    1.13 +// BEGIN: design.composition.arith2.0.compat
    1.14 +public class Arithmetica {
    1.15 +    private final int version;
    1.16 +    
    1.17 +    public Arithmetica() {
    1.18 +        this(1);
    1.19 +    }
    1.20 +    public Arithmetica(int version) {
    1.21 +        this.version = version;
    1.22 +    }
    1.23 +    
    1.24 +    public int sumTwo(int one, int second) {
    1.25 +        return one + second;
    1.26 +    }
    1.27 +    
    1.28 +    public int sumAll(int... numbers) {
    1.29 +        if (numbers.length == 0) {
    1.30 +            return 0;
    1.31 +        }
    1.32 +        int sum = numbers[0];
    1.33 +        for (int i = 1; i < numbers.length; i++) {
    1.34 +            sum = sumTwo(sum, numbers[i]);
    1.35 +        }
    1.36 +        return sum;
    1.37 +    }
    1.38 +    
    1.39 +    public int sumRange(int from, int to) {
    1.40 +        switch (version) {
    1.41 +            case 1: return sumRange1(from, to);
    1.42 +            case 2: return sumRange2(from, to);
    1.43 +            default: throw new IllegalStateException();
    1.44 +        }
    1.45 +    }
    1.46 +
    1.47 +    private int sumRange1(int from, int to) {
    1.48 +        int len = to - from;
    1.49 +        if (len < 0) {
    1.50 +            len = -len;
    1.51 +            from = to;
    1.52 +        }
    1.53 +        int[] array = new int[len + 1];
    1.54 +        for (int i = 0; i <= len; i++) {
    1.55 +            array[i] = from + i;
    1.56 +        }
    1.57 +        return sumAll(array);
    1.58 +    }
    1.59 +    
    1.60 +    private int sumRange2(int from, int to) {
    1.61 +        return (from + to) * (Math.abs(to - from) + 1) / 2;
    1.62 +    }
    1.63 +}
    1.64 +// END: design.composition.arith2.0.compat