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