英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论