簡體   English   中英

如何比較 (x,y) 點進行排序,其中 x 始終排在第一位

[英]How to compare (x,y) points for sorting, where x is always first

我正在使用 Java Comparator 將位置對象與點 (x,y) 進行比較。

我需要能夠比較兩個點以檢索一個正整數或負整數,這將允許我對 (x,y) 點進行排序,其中首先對 x 值進行排序,然后對 y 值進行排序。 (如果這是有道理的......)例如,這個:

(3,4) (2,5) (1,1) (1,3) (3,3)

變成這樣:

(1,1) (1,3) (2,5) (3,3) (3,4)

我想這樣做的一種方法基本上是通過將 x 值乘以像 1000 這樣的大數來賦予 x 值較大的優先級。像這樣:比較 (3,3) 和 (1,1):

int x_multiplier = 1000;
int value1 = (p1.x * x_multiplier ) + p1.y; // = 3 * 1000 + 3 = 3003
int value2 = (p2.x * x_multiplier ) + p2.y; // = 1 * 1000 + 1 = 1001
return value1-value2; // = 2002. Value1 is greater, thus p1 be later in list.

這是有效的,但問題是如果 Y 值應該等於或大於 x_multiplier,那么它就會崩潰(因為 y 值現在等於 1 x 值......再次,如果說得通。)

// Comparing p1 = (2,0) & p2 = (1,18)
int x_multiplier = 10;
int value1 = (p1.x * x_multiplier ) + p1.y; // = 2 * 10 + 0  = 20
int value2 = (p2.x * x_multiplier ) + p2.y; // = 1 * 10 + 18 = 28
return value1-value2; // = -8, value2 is greater, and thus p2 will be later in the list. However, we know by looking at the points that p2 should come first.

我什至不知道如何搜索這個,所以如果有答案,我找不到它們。

import java.util.*;

class Tuple {
    public int x, y;

    Tuple(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ") ";
    }
}

public class coord {
    public static void main(String[] args) {
        LinkedList<Tuple> list = new LinkedList<Tuple>();
        list.add(new Tuple(3,4));
        list.add(new Tuple(2,5));
        list.add(new Tuple(1,1));
        list.add(new Tuple(1,3));
        list.add(new Tuple(3,3));
        for (Tuple t: list) {
            System.out.print(t);
        }
        Collections.sort(list, (Tuple t1, Tuple t2) -> {
            int result = Integer.compare(t1.x, t2.x);
            if (result == 0 ) result = Integer.compare(t1.y, t2.y);
            return result;
        });
        System.out.println("Sorted List: ");
        for (Tuple t: list) {
            System.out.print(t);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM