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