author | Jaroslav Tulach <jtulach@netbeans.org> |
Sat, 14 Jun 2008 09:58:05 +0200 | |
changeset 152 | eb6f29070331 |
parent 149 | eb52f31b18f4 |
child 184 | 6b2cd8df14c0 |
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@148 | 17 |
int sum = numbers[0]; |
jtulach@148 | 18 |
for (int i = 1; i < numbers.length; i++) { |
jtulach@148 | 19 |
sum = sumTwo(sum, numbers[i]); |
jtulach@148 | 20 |
} |
jtulach@148 | 21 |
return sum; |
jtulach@148 | 22 |
} |
jtulach@148 | 23 |
|
jtulach@148 | 24 |
public int sumRange(int from, int to) { |
jtulach@149 | 25 |
// BEGIN: design.composition.arith2.0.property.if |
jtulach@148 | 26 |
if (Boolean.getBoolean("arithmetica.v2")) { |
jtulach@148 | 27 |
return sumRange2(from, to); |
jtulach@148 | 28 |
} else { |
jtulach@148 | 29 |
return sumRange1(from, to); |
jtulach@148 | 30 |
} |
jtulach@149 | 31 |
// END: design.composition.arith2.0.property.if |
jtulach@148 | 32 |
} |
jtulach@148 | 33 |
|
jtulach@148 | 34 |
private int sumRange1(int from, int to) { |
jtulach@148 | 35 |
int len = to - from; |
jtulach@148 | 36 |
int[] array = new int[len + 1]; |
jtulach@148 | 37 |
for (int i = 0; i <= len; i++) { |
jtulach@148 | 38 |
array[i] = from + i; |
jtulach@148 | 39 |
} |
jtulach@148 | 40 |
return sumAll(array); |
jtulach@148 | 41 |
} |
jtulach@148 | 42 |
|
jtulach@148 | 43 |
private int sumRange2(int from, int to) { |
jtulach@148 | 44 |
return (from + to) * (to - from + 1) / 2; |
jtulach@148 | 45 |
} |
jtulach@152 | 46 |
} |
jtulach@148 | 47 |
// END: design.composition.arith2.0.property |