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.

0

1 Answer 1

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
}

Sign up to request clarification or add additional context in comments.

2 Comments

distance() method should be static, and you calculate 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.
Ahh duh. Thanks for the clarification!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.