문제

I have a list of Point and I want to sort them with their neighbour.

For exemple :
List init

(0,0); (1,0); (5,0); (6,0);  
(0,1); (1,1); (5,1); (6,1);  

List sorted

(0,0); (1,0); (0,1); (1,1);  
(5,0); (6,0); (5,1); (6,1);  

How can I do that ?

list.sort(new Comparator<Point>() {
    @Override
    public int compare(Point p1, Point p2) {
        // Euclidian distance or something like that
        return ;
    }
});
도움이 되었습니까?

해결책 2

You need an algorithm that does this, starting with a set of points.

  1. If there are no points in the set, then stop.
  2. Make a new set (the current object), and choose any point out of the original set to be the first point in the new set.
  3. Remove the chosen point from the set and add it to the current object.
  4. Check each of the chosen point's eight neighbours to see if any are in the original set.
  5. For any point thus found, run this algorithm starting from step 3 (use recursion for this).
  6. If none of the neighbours were in the original set, go back to step 1.

다른 팁

Implement Comparator to get the ordering you want. Example:

Collections.sort(list, new Comparator<Point>()
{
    public int compare(Point p1, Point p2)
    {
        //Euclidean distance from 0,0
        Point origin = new Point();
        return Double.compare(p1.distance(origin), p2.distance(origin));
    }
});

or, with java 8 lambda expressions:

Collections.sort(list, ((p1, p2) -> Double.compare(p1.distance(0, 0), p2.distance(0, 0));

Implement Comparator in your class and use a Collection which orders elements using comparator, or use use Collections.sort(List, Comparator)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top