ingo@1115: /* ingo@1115: * Copyright (c) 2010 by Intevation GmbH ingo@1115: * ingo@1115: * This program is free software under the LGPL (>=v2.1) ingo@1115: * Read the file LGPL.txt coming with the software for details ingo@1115: * or visit http://www.gnu.org/licenses/ if it does not exist. ingo@1115: */ ingo@1115: sascha@361: package de.intevation.gnv.math; sascha@361: sascha@779: import com.vividsolutions.jts.geom.Coordinate; sascha@779: sascha@361: import java.util.Comparator; sascha@361: sascha@361: /** sascha@807: * Compares two coordinates a and b by their L1(Manhattan) distance sascha@805: * relative to a reference point r. sascha@805: * da = L1(a, r)
sascha@805: * db = L1(b, r)
sascha@805: * -1 if da < db, +1 if da > db, 0 else. sascha@798: * @author Sascha L. Teichmann sascha@361: */ sascha@361: public class L1Comparator sascha@361: implements Comparator sascha@361: { sascha@361: private Coordinate ref; sascha@361: sascha@805: /** sascha@805: * Default constructor. sascha@805: */ sascha@474: public L1Comparator() { sascha@474: } sascha@474: sascha@805: /** sascha@805: * Constructor to create a L1Comparator with a given reference point. sascha@805: * @param ref The reference point. sascha@805: */ sascha@361: public L1Comparator(Coordinate ref) { sascha@361: this.ref = ref; sascha@361: } sascha@361: sascha@805: /** sascha@805: * Explicitly sets the reference point. sascha@805: * @param ref The reference point. sascha@805: */ sascha@474: public void setReference(Coordinate ref) { sascha@474: this.ref = ref; sascha@474: } sascha@474: sascha@805: /** sascha@805: * Compares to coordinate by their L1 distance to the reference point. sascha@805: * @param a The first coordinate. sascha@805: * @param b The second coordinate. sascha@805: * @return -1 if L1(a, ref) < L1(b, ref), sascha@805: * +1 if L1(a, ref) > L1(b, ref), 0 else. sascha@805: */ sascha@361: public int compare(Object a, Object b) { sascha@361: Coordinate pa = (Coordinate)a; sascha@361: Coordinate pb = (Coordinate)b; sascha@798: double da = L1(ref, pa); sascha@798: double db = L1(ref, pb); sascha@361: if (da < db) return -1; sascha@361: if (da > db) return +1; sascha@361: return 0; sascha@361: } sascha@798: sascha@805: /** sascha@805: * Computes the L1 distance between two points a and b:
sascha@805: * L1(a, b) = abs(a.x - b.x) + abs(a.y - b.y) sascha@805: * @param a The first point. sascha@805: * @param b The second point. sascha@805: * @return The L1 distance. sascha@805: */ sascha@798: public static double L1(Coordinate a, Coordinate b) { sascha@798: return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); sascha@798: } sascha@361: } sascha@798: // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :