jtulach@147: package api; jtulach@147: jtulach@147: /** Class to simplify arithmetical operations, improved version to compute jtulach@147: * the sum for ranges, but only if one uses the new constructor to indicate jtulach@147: * need for new version. jtulach@147: * jtulach@147: * @author Jaroslav Tulach jtulach@147: * @version 2.0 jtulach@147: */ jtulach@147: // BEGIN: design.composition.arith2.0.compat jtulach@147: public class Arithmetica { jtulach@147: private final int version; jtulach@147: jtulach@147: public Arithmetica() { jtulach@147: this(1); jtulach@147: } jtulach@147: public Arithmetica(int version) { jtulach@147: this.version = version; jtulach@147: } jtulach@147: jtulach@147: public int sumTwo(int one, int second) { jtulach@147: return one + second; jtulach@147: } jtulach@147: jtulach@147: public int sumAll(int... numbers) { jtulach@187: if (numbers.length == 0) { jtulach@187: return 0; jtulach@187: } jtulach@147: int sum = numbers[0]; jtulach@147: for (int i = 1; i < numbers.length; i++) { jtulach@147: sum = sumTwo(sum, numbers[i]); jtulach@147: } jtulach@147: return sum; jtulach@147: } jtulach@147: jtulach@147: public int sumRange(int from, int to) { jtulach@147: switch (version) { jtulach@147: case 1: return sumRange1(from, to); jtulach@147: case 2: return sumRange2(from, to); jtulach@147: default: throw new IllegalStateException(); jtulach@147: } jtulach@147: } jtulach@147: jtulach@147: private int sumRange1(int from, int to) { jtulach@147: int len = to - from; jtulach@210: if (len < 0) { jtulach@210: len = -len; jtulach@210: from = to; jtulach@210: } jtulach@147: int[] array = new int[len + 1]; jtulach@147: for (int i = 0; i <= len; i++) { jtulach@147: array[i] = from + i; jtulach@147: } jtulach@147: return sumAll(array); jtulach@147: } jtulach@147: jtulach@147: private int sumRange2(int from, int to) { jtulach@210: return (from + to) * (Math.abs(to - from) + 1) / 2; jtulach@147: } jtulach@152: } jtulach@147: // END: design.composition.arith2.0.compat