1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| interface Constraint {
boolean isSatisfied(double d);
String getName();
}
class ConstraintLess10 implements Constraint {
public boolean isSatisfied(double d) {
return d < 10;
}
public String getName() {
return "< 10";
}
}
class ConstraintBetween10And20 implements Constraint {
public boolean isSatisfied(double d) {
return d >= 10 && d < 20;
}
public String getName() {
return ">= 10 et < 20";
}
}
// autres contraintes
...
// qq part
public Map partition(double[] array, List constraints) {
Map map = new HashMap();
for (int i = 0; i < array.length; i++) {
double d = array[i];
select(d, constraints, map);
}
return map;
}
private void select(double d, List constraints, Map map) {
for (Iterator it = constraints.iterator(); it.hasNext();) {
Constraint constraint = (Constraint) it.next();
if (constraint.isSatisfied(d)) {
List doubles = (List) map.get(constraint);
if (doubles == null) {
doubles = new ArrayList();
map.put(constraint, doubles);
}
doubles.add(new Double(d));
}
}
}
public void print(Map map, PrintStream out) {
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Entry entry = (Entry) map.next();
Constraint constraint = (Constraint) entry.getKey();
List doubles = (List) entry.getValue() ;
StringBuffer sb = new StringBuffer();
for (Iterator it2 = doubles.iterator(); it.hasNext();) {
sb.append(it2.next()).append(" ");
}
out.println("contrainte " + constraint.getName() + " satisfaite pour " + sb);
}
}
Map map = partition(new double[] {
10.1, 34.0, 15.0, 22.5, 24.2, 31.0, 32.0, 37.0 },
Arrays.asList(new Constraint[] {
new ConstraintLess10(),
new ConstraintBetween10And20(),
...})); |
Partager