如何在Kotlin中使用比较器和lambda函数按列对2D数组进行排序?

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

How to sort 2D array in kotlin according to it's column using comparator & lamda function?

问题

在Kotlin中,你可以使用sortBy函数来按照第3列对2D数组进行排序。以下是你的Kotlin代码示例,其中包括如何进行排序:

  1. fun main() {
  2. val rows = 3
  3. val cols = 4
  4. val arr = Array(rows) { r -> IntArray(cols) { c -> r + ((Math.random() * 9).toInt()) } }
  5. for (row in arr) {
  6. println(row.contentToString())
  7. }
  8. // 在这里按第3列排序
  9. arr.sortBy { it[2] }
  10. for (row in arr) {
  11. println(row.contentToString())
  12. }
  13. }

这将根据第3列的值对2D数组进行升序排序。

英文:

I want to sort 2D array in Kotlin, I know how to do it in java but it is not working in Kotlin, there must be a different syntax. I surfed on the internet but couldn't find a direct syntax solution.

I am creating a random 2D array and I want to sort it with respect to it's 3rd column.

  1. fun main(){
  2. val rows = 3
  3. val cols = 4
  4. val arr = Array(rows) { r -> IntArray(cols) { c -> r + ((Math.random()*9).toInt()) } }
  5. for (row in arr) {
  6. println(row.contentToString())
  7. }
  8. // I want to sort here
  9. // In Java I would do this: Arrays.sort(arr, Comparator.comparingDouble( o -> o[2] ))
  10. }

How to do the same in Kotlin, in Java I can sort it in the following manner:

  1. Arrays.sort(arr, Comparator.comparingDouble( o -> o[2] ))

How to do the same in Kotlin syntax?

答案1

得分: 0

使用sortBy方法将允许您返回所选的排序标准。

  1. import kotlin.random.Random
  2. import kotlin.random.nextInt
  3. val rows = 3
  4. val cols = 4
  5. val arr = Array(rows) { r ->
  6. IntArray(cols) {
  7. r + Random.nextInt(1..5) * 9
  8. }
  9. }
  10. fun printArr() {
  11. for (row in arr) {
  12. println(row.contentToString())
  13. }
  14. }
  15. printArr()
  16. arr.sortBy { it[2] }
  17. printArr()
  18. // 生成的结果:
  19. // [36, 45, 45, 45]
  20. // [19, 37, 28, 19]
  21. // [11, 38, 11, 38]
  22. // 输出结果:
  23. // [11, 38, 11, 38]
  24. // [19, 37, 28, 19]
  25. // [36, 45, 45, 45]

请注意,这是您提供的代码的中文翻译。

英文:

Using the method sortBy will allow you to return the selected sorting criteria.

  1. import kotlin.random.Random
  2. import kotlin.random.nextInt
  3. val rows = 3
  4. val cols = 4
  5. val arr = Array(rows) { r ->
  6. IntArray(cols) {
  7. r + Random.nextInt(1..5) * 9
  8. }
  9. }
  10. fun printArr() {
  11. for (row in arr) {
  12. println(row.contentToString())
  13. }
  14. }
  15. printArr()
  16. arr.sortBy { it[2] }
  17. printArr()
  18. // Generated:
  19. // [36, 45, 45, 45]
  20. // [19, 37, 28, 19]
  21. // [11, 38, 11, 38]
  22. // Output:
  23. // [11, 38, 11, 38]
  24. // [19, 37, 28, 19]
  25. // [36, 45, 45, 45]

huangapple
  • 本文由 发表于 2023年3月9日 22:45:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686148.html
匿名

发表评论

匿名网友

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

确定