如何使用第二个索引来进行二维数组的排序,用于解决平局。

huangapple go评论75阅读模式
英文:

How to sort a 2d array using the second index for tiebreaks

问题

请注意,您提供的代码部分已被保留,我将为您提供翻译后的代码部分:

Arrays.sort(input, (a, b) -> {
    int c1 = a[0];
    int c2 = b[0];
    if (c1 == c2) return a[1] - b[1];
    return c1 - c2;
});

这段代码是用Java中的Lambda表达式对一个二维数组进行排序的示例,如果需要进行二次排序(tiebreak),它会比较第二个元素。如果数组是 { {1,0}, {2,5}, {1,55} },排序后会变成 { {1,0}, {1,55}, {2,5} }。希望这可以帮助您解决问题!

英文:

Anyone know the correct syntax for sorting an 2d array using Lambdas in java where in the need to tiebreak we move on to the second element?
like if the array is { {1,0}, {2,5}, {1,55}}
it becomes {{1,0}, {1,55}, {2,5}}

So Im familair that the syntax for just sorting the array as input follows the syntax of

     ```java
         Arrays.sort(input, (a, b) -> (a[0] - b[0));
      ```

I have tried some of my own experimental ways around this, such as

```java
 Arrays.sort(input, (a,b) ->
  int c1 = a[0];
  int c2 = b[0];
if(c1 == c2) return a[1] - b[1];
   return c1 - c2;
);

but these still have syntax errors in various places. Any help is appreciated!

答案1

得分: 3

在lambda主体包含多个表达式时,需要在lambda主体周围使用括号。此外,应首选Integer.compare而不是减法(考虑溢出)。

Arrays.sort(input, (a, b) -> {
    int c1 = a[0];
    int c2 = b[0];
    if (c1 == c2) return Integer.compare(a[1], b[1]);
    return Integer.compare(c1, c2);
});

这可以简化为使用Comparator方法。

Arrays.sort(input, Comparator.<int[]>comparingInt(x -> x[0]).thenComparingInt(x -> x[1]));

Arrays.compare将此数组的字典顺序推广到任意长度的数组(正如Eritrean所提到的)。

Arrays.sort(input, Arrays::compare);
英文:

You need braces around the lambda body when it consists of more than one expression. Also, Integer.compare should be preferred over subtracting (consider overflow).

Arrays.sort(input, (a, b) -&gt; {
    int c1 = a[0];
    int c2 = b[0];
    if (c1 == c2) return Integer.compare(a[1], b[1]);
    return Integer.compare(c1, c2);
});

This can be simplified with Comparator methods.

Arrays.sort(input, Comparator.&lt;int[]&gt;comparingInt(x -&gt; x[0]).thenComparingInt(x -&gt; x[1]));

Arrays.compare generalizes this lexicographic order for arrays of any length (as mentioned by Eritrean).

Arrays.sort(input, Arrays::compare);

huangapple
  • 本文由 发表于 2023年7月7日 02:00:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定