samples/composition/src-api2.0-enum/org/apidesign/math/Arithmetica.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 21:30:10 +0100
changeset 409 40cabcdcd2be
parent 210 acf2c31e22d4
permissions -rw-r--r--
Updating to NBMs from NetBeans 8.0.1 as some of them are required to run on JDK8
     1 package org.apidesign.math;
     2 
     3 /** Class to simplify arithmetical operations, improved version to compute
     4  * the sum for ranges, but only if one uses the new constructor to indicate
     5  * need for new version.
     6  *
     7  * @author Jaroslav Tulach <jtulach@netbeans.org>
     8  * @version 2.0
     9  */
    10 // BEGIN: design.composition.arith2.0.enum
    11 public class Arithmetica {
    12     private final Version version;
    13     public enum Version { VERSION_1_0, VERSION_2_0 }
    14     
    15     public Arithmetica() {
    16         this(Version.VERSION_1_0);
    17     }
    18     public Arithmetica(Version version) {
    19         this.version = version;
    20     }
    21 
    22     public int sumRange(int from, int to) {
    23         switch (version) {
    24             case VERSION_1_0:
    25                 return sumRange1(from, to);
    26             case VERSION_2_0:
    27                 return sumRange2(from, to);
    28             default:
    29                 throw new IllegalStateException();
    30         }
    31     }
    32 // FINISH: design.composition.arith2.0.enum
    33     
    34     public int sumTwo(int one, int second) {
    35         return one + second;
    36     }
    37     
    38     public int sumAll(int... numbers) {
    39         if (numbers.length == 0) {
    40             return 0;
    41         }
    42         int sum = numbers[0];
    43         for (int i = 1; i < numbers.length; i++) {
    44             sum = sumTwo(sum, numbers[i]);
    45         }
    46         return sum;
    47     }
    48     
    49 
    50     private int sumRange1(int from, int to) {
    51         int len = to - from;
    52         if (len < 0) {
    53             len = -len;
    54             from = to;
    55         }
    56         int[] array = new int[len + 1];
    57         for (int i = 0; i <= len; i++) {
    58             array[i] = from + i;
    59         }
    60         return sumAll(array);
    61     }
    62     
    63     private int sumRange2(int from, int to) {
    64         return (from + to) * (Math.abs(to - from) + 1) / 2;
    65     }
    66 }