Partition { public Partition reduce() { if (d_reduced) { return this; } UndirectedGraph<Treatment, Part> graph = buildGraph(d_parts); if (graph == null) { return this; } Treatment v0 = CompareUtil.findLeast(graph.getVertices(), TreatmentComparator.INSTANCE); Part p = graph.getIncidentEdges(v0).iterator().next(); Pair<Treatment> treatments = new Pair<Treatment>(v0, otherTreatment(p, v0)); Set<Part> visited = new HashSet<Part>(); Treatment tRight = walk(graph, p, treatments.getFirst(), visited); if (tRight.equals(treatments.getFirst())) { return new Partition(Collections.singleton(new Part(tRight, tRight, p.getStudies()))); } Treatment tLeft = walk(graph, p, treatments.getSecond(), visited); Set<Part> reduced = new HashSet<Part>(); reduced.add(new Part(tRight, tLeft, p.getStudies())); do { p = nextPart(graph, visited, tRight); Treatment tNext = walk(graph, p, tRight, visited); reduced.add(new Part(tRight, tNext, p.getStudies())); tRight = tNext; } while (!tRight.equals(tLeft)); Partition partition = new Partition(reduced); partition.d_reduced = true; return partition; } Partition(Collection<Part> parts); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Set<Part> getParts(); Partition reduce(); List<Treatment> asCycle();  }
@Test public void testReduce() { assertEquals(new Partition(Collections.singleton(d_p6)), new Partition(Arrays.asList(d_p3, d_p4, d_p5)).reduce()); assertEquals(new Partition(Arrays.asList(d_p7, d_p3)), new Partition(Arrays.asList(d_p7, d_p4, d_p5)).reduce()); assertEquals(new Partition(Arrays.asList(d_p8, d_p5)), new Partition(Arrays.asList(d_p3, d_p8, d_p4)).reduce()); assertEquals(new Partition(Arrays.asList(d_p7, d_p8, d_p4)), new Partition(Arrays.asList(d_p7, d_p8, d_p4)).reduce()); }
@Test public void testLongerCycle() { Treatment ta = new Treatment("A"); Treatment tb = new Treatment("B"); Treatment tc = new Treatment("C"); Treatment td = new Treatment("D"); Study s1 = new Study("1"); s1.getMeasurements().addAll(Arrays.asList(new Measurement(ta), new Measurement(tb))); Study s2 = new Study("2"); s2.getMeasurements().addAll(Arrays.asList(new Measurement(tb), new Measurement(tc), new Measurement(td))); Study s3 = new Study("3"); s3.getMeasurements().addAll(Arrays.asList(new Measurement(ta), new Measurement(td))); Study s4 = new Study("4"); s4.getMeasurements().addAll(Arrays.asList(new Measurement(tc), new Measurement(td))); Part p1 = new Part(ta, tb, Arrays.asList(s1)); Part p2 = new Part(tb, tc, Arrays.asList(s2)); Part p3 = new Part(tc, td, Arrays.asList(s2, s4)); Part p4 = new Part(td, ta, Arrays.asList(s3)); Partition partition = new Partition(Arrays.asList(p1, p2, p3, p4)); assertEquals(partition, partition.reduce()); }