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

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

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

问题

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

fun main() {
    val rows = 3
    val cols = 4

    val arr = Array(rows) { r -> IntArray(cols) { c -> r + ((Math.random() * 9).toInt()) } }
    for (row in arr) {
        println(row.contentToString())
    }

    // 在这里按第3列排序
    arr.sortBy { it[2] }
    
    for (row in arr) {
        println(row.contentToString())
    }
}

这将根据第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.

fun main(){
        val rows = 3
        val cols = 4

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

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

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

How to do the same in Kotlin syntax?

答案1

得分: 0

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

import kotlin.random.Random
import kotlin.random.nextInt

val rows = 3
val cols = 4

val arr = Array(rows) { r ->
    IntArray(cols) {
        r + Random.nextInt(1..5) * 9
    }
}

fun printArr() {
    for (row in arr) {
        println(row.contentToString())
    }
}

printArr()
arr.sortBy { it[2] }
printArr()

// 生成的结果:
// [36, 45, 45, 45]
// [19, 37, 28, 19]
// [11, 38, 11, 38]

// 输出结果:
// [11, 38, 11, 38]
// [19, 37, 28, 19]
// [36, 45, 45, 45]

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

英文:

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

import kotlin.random.Random
import kotlin.random.nextInt

val rows = 3
val cols = 4

val arr = Array(rows) { r -> 
    IntArray(cols) {
        r + Random.nextInt(1..5) * 9
    }
}

fun printArr() {
    for (row in arr) {
        println(row.contentToString())
    } 
}

printArr()
arr.sortBy { it[2] }
printArr()

// Generated:
// [36, 45, 45, 45]
// [19, 37, 28, 19]
// [11, 38, 11, 38]

// Output:
// [11, 38, 11, 38]
// [19, 37, 28, 19]
// [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:

确定