All pastes #885090 Raw Edit

Miscellany

public text v1 · immutable
#885090 ·published 2008-01-30 19:24 UTC
rendered paste body
import java.util.*;
class Storer<P extends Positioned>{
    public Storer( int size ) {
        this.size = size;
    }
    public void add( P p ) {
        points.add( p );
    }
    public void rem( P p ) {
        points.remove( p );
    }
    public P closestTo( P a ) {
        double[] apos = a.getPos();
        P minp = null;
        double mind = -1;
        for (P p : points) {
            double dist = getDistance( apos, p.getPos() );
            if ( mind == -1 || dist < mind ) {
                minp = p;
                mind = dist;
            }
        }
        return minp;
    }
    private double getDistance( double[] a, double[] b) {
        // In some languages, this function would be shorter than the following name... I guess that's Java for ya :)
        double distsSquareSum = 0;
        int i = 0;
        for ( ; i < a.length && i < b.length; i += 1) {
            double dif = (b[i] - a[i]);
            distsSquareSum += dif * dif;
        }
        for ( ; i < a.length || i < b.length; i += 1 ) {
            if ( i < a.length )
                distsSquareSum += a[i] * a[i];
            else
                distsSquareSum += b[i] * b[i];
        }
        return Math.sqrt( distsSquareSum );
    }
    public static void main( String[] args ) {
        // The argument 4 specifies the number of dimensions.
        Storer< Point >s = new Storer< Point >( 4 );
        // Some content for s.
        s.add( new Point( new double[] {3, 9, 7, 4} ) );
        s.add( new Point( new double[] {7, 2, 0, 4} ) );
        s.add( new Point( new double[] {1, 7, 2, 4} ) );
        s.add( new Point( new double[] {6, 3, 1, 8} ) );
        // Make testpoint, and find the closest point to it in s, then print that
        Point testPoint = new Point( new double[] {6, 6, 6, 6} );
        Point closest = s.closestTo( testPoint );
        System.out.println( closest.toString() );
    }
    private ArrayList< P > points = new ArrayList< P >( );
    private int size;
}

interface Positioned {
    public double[] getPos();
}

class Point implements Positioned {
    public Point( double[] pos ) {
        this.pos = pos;
    }
    public double[] getPos( ) {
        return pos;
    }
    public String toString( ) {
        String sb = "[";
        for (double i : pos) {
            sb += i;
            sb += "; ";
        }
        return sb + "]";
    }
    private final double[] pos;
}