author | Jaroslav Tulach <jtulach@netbeans.org> |
Sat, 14 Jun 2008 10:01:18 +0200 | |
changeset 184 | 6b2cd8df14c0 |
parent 152 | eb6f29070331 |
child 186 | 09d10795f55c |
permissions | -rw-r--r-- |
jtulach@148 | 1 |
package api; |
jtulach@148 | 2 |
|
jtulach@148 | 3 |
/** Class to simplify arithmetical operations, improved version to compute |
jtulach@148 | 4 |
* the sum for ranges, but only if the virtual machine is configured to |
jtulach@148 | 5 |
* run in incompatible mode. |
jtulach@148 | 6 |
* |
jtulach@148 | 7 |
* @author Jaroslav Tulach <jtulach@netbeans.org> |
jtulach@148 | 8 |
* @version 2.0 |
jtulach@148 | 9 |
*/ |
jtulach@148 | 10 |
// BEGIN: design.composition.arith2.0.property |
jtulach@148 | 11 |
public class Arithmetica { |
jtulach@148 | 12 |
public int sumTwo(int one, int second) { |
jtulach@148 | 13 |
return one + second; |
jtulach@148 | 14 |
} |
jtulach@148 | 15 |
|
jtulach@148 | 16 |
public int sumAll(int... numbers) { |
jtulach@184 | 17 |
if (numbers.length == 0) { |
jtulach@184 | 18 |
return 0; |
jtulach@184 | 19 |
} |
jtulach@148 | 20 |
int sum = numbers[0]; |
jtulach@148 | 21 |
for (int i = 1; i < numbers.length; i++) { |
jtulach@148 | 22 |
sum = sumTwo(sum, numbers[i]); |
jtulach@148 | 23 |
} |
jtulach@148 | 24 |
return sum; |
jtulach@148 | 25 |
} |
jtulach@148 | 26 |
|
jtulach@148 | 27 |
public int sumRange(int from, int to) { |
jtulach@149 | 28 |
// BEGIN: design.composition.arith2.0.property.if |
jtulach@148 | 29 |
if (Boolean.getBoolean("arithmetica.v2")) { |
jtulach@148 | 30 |
return sumRange2(from, to); |
jtulach@148 | 31 |
} else { |
jtulach@148 | 32 |
return sumRange1(from, to); |
jtulach@148 | 33 |
} |
jtulach@149 | 34 |
// END: design.composition.arith2.0.property.if |
jtulach@148 | 35 |
} |
jtulach@148 | 36 |
|
jtulach@148 | 37 |
private int sumRange1(int from, int to) { |
jtulach@148 | 38 |
int len = to - from; |
jtulach@148 | 39 |
int[] array = new int[len + 1]; |
jtulach@148 | 40 |
for (int i = 0; i <= len; i++) { |
jtulach@148 | 41 |
array[i] = from + i; |
jtulach@148 | 42 |
} |
jtulach@148 | 43 |
return sumAll(array); |
jtulach@148 | 44 |
} |
jtulach@148 | 45 |
|
jtulach@148 | 46 |
private int sumRange2(int from, int to) { |
jtulach@148 | 47 |
return (from + to) * (to - from + 1) / 2; |
jtulach@148 | 48 |
} |
jtulach@152 | 49 |
} |
jtulach@148 | 50 |
// END: design.composition.arith2.0.property |