Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Point;
- import java.util.ArrayList;
- public class TestDistance {
- /**
- * Testing the average time to get the distance to the closest point.
- *
- * I am using average because sometimes java will run slow and sometimes run fast...
- * Running a lot of results and getting the average seems to be the most reliable method.
- *
- * @param args
- */
- public static void main(String[] args){
- long start, end;
- Point p = new Point(0,0);
- ArrayList<Point> points = new ArrayList<Point>();
- ArrayList<Long> results = new ArrayList<Long>();
- ArrayList<Double> results2 = new ArrayList<Double>();
- int pstart = 10;
- for(int w = 0; w < 3; w++){
- //Assign points.
- for(int a = 0; a < pstart; a++)
- for(int b = 0; b < pstart; b++)
- points.add(new Point(a,b));
- //Loop over to get average
- for(int z = 0; z < 10; z++){
- //Loop 100 times to get a average
- for(int i = 0; i < 100; i++){
- start = System.currentTimeMillis();
- getClosest(p,points);
- end = System.currentTimeMillis() - start;
- results.add(end);
- //System.out.println("Time taken: " + end + " ms.");
- }
- results2.add(calculateAverageLong(results));
- //System.out.println("Average time (Out of 100): " + calculateAverage(results) + "ms to find the closest point out of " + points.size() + " points.");
- results.clear();
- }
- System.out.println("Average time TOTAL (10 loops of 100 loops): " + calculateAverageDouble(results2) + "ms to find the closest point out of " + points.size() + " points.");
- results2.clear();
- points.clear();
- //Increase points to check
- switch(pstart){
- case 100:
- pstart = 1000;
- break;
- case 10:
- pstart = 100;
- break;
- }
- }
- }
- /**
- * Calculate the average for longs.
- *
- * @param marks
- * @return Long
- */
- private static double calculateAverageLong(ArrayList<Long> marks) {
- Long sum = 0L;
- for(Long mark : marks)
- sum += mark;
- return (sum.doubleValue() / marks.size());
- }
- /**
- * Calculate the average for doubles.
- *
- * @param marks
- * @return Double
- */
- private static double calculateAverageDouble(ArrayList<Double> marks) {
- Double sum = 0D;
- for(Double mark : marks)
- sum += mark;
- return sum / marks.size();
- }
- /**
- * Get the closest point.
- *
- * @param start
- * @param points
- * @return Point
- */
- public static Point getClosest(Point start, ArrayList<Point> points) {
- Point closest = null;
- double hold = 0;
- int nearest = 999999;
- for(Point p : points){
- if(p != null){
- hold = p.distance(start);
- if(hold < nearest){
- nearest = (int) p.distance(start);
- closest = p;
- }
- }
- }
- return closest;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement