0

I have an ArrayList of ints[] that I would like to sort based on the distance from a specific position.

Example. ArrayList<int[]> = {-2,-3},{2,3}, {1,2}

Specific position = {1,1}

After sorting: {1,2}, {2,3}, {-2,-3}

I know I can just subtract {1,1} from every int[] then create a Comparator for the magnitudes--but my question specifically is how to do it without subtracting {1,1} first.

1 Answers1

0

Make a custom 'translator' function, and then make a comparator to compare on this function:


int[] ORIGIN = {1, 1};
list.sort(Comparator.comparingDouble(a -> distance(ORIGIN, a));

public double distance(int[] a, int[] b) {
    // not sure how one calculates this distance thing,
    // but do it here
}

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • `distance()` method should be `static`, and you calculate [distance between two points](https://www.google.com/search?q=distance+between+two+points) like normally, i.e. square root of sum of squares: `sqrt( (a[0] - b[0])^2 + (a[1] - b[1])^2 )` where `^2` means squared. Since you are comparing the results relatively, the `sqrt` part can be skipped, for better performance. – Andreas Jul 20 '20 at 19:29
  • Ahh duh. Thanks for the clarification! – Christopher Clark Jul 20 '20 at 19:31