package com.github.davidmoten.rtree;

import java.util.ArrayList;
import java.util.List;

import com.github.davidmoten.rtree.geometry.Geometry;
import com.github.davidmoten.rtree.geometry.Rectangle;
import com.google.common.base.Optional;

public class SelectorMinimalOverlap implements Selector {

	@Override
	public <T> Node<T> select(Geometry g, List<? extends Node<T>> nodes) {
		return findMinimalOverlap(g.mbr(), nodes);
	}

	private static <T> Node<T> findMinimalOverlap(Rectangle r,
			List<? extends Node<T>> list) {
		List<Node<T>> best = new ArrayList<Node<T>>();
		Optional<Double> bestMetric = Optional.absent();
		for (Node<T> node : list) {
			double m = 0;
			for (Node<T> node2 : list) {
				if (node2 != node) {
					m += node.geometry().mbr().add(r)
							.intersectionArea(node2.geometry().mbr());
				}
			}
			if (!bestMetric.isPresent() || m < bestMetric.get()) {
				best = new ArrayList<Node<T>>();
				best.add(node);
				bestMetric = Optional.of(m);
			} else if (bestMetric.isPresent() && m == bestMetric.get()) {
				best.add(node);
			}
		}
		return SelectorMinimalAreaIncrease.findMinimalAreaIncrease(r, best);
	}
}

@@ -706,37 +706,28 @@
 %09%09%09%09
-if (node2 != node) %7B%0A%09%09%09%09%09m +
+Rectangle nodePlusR 
 = no
@@ -756,16 +756,54 @@
 d(r)
+;
 %0A%09%09%09%09
-%09%09%09
+if (node2 != node) %7B%0A%09%09%09%09%09m += nodePlusR
 .int

optimise minimal overlap selector