我正在為一個學校專案作業,我需要使用 Kotlin 對多維陣列進行排序。該陣列包含獎牌陣列。我需要像獎牌表一樣對其進行排序,這取決于獎牌的重量和獎牌的數量。
陣列是這樣的:
[0] -> [0,0,0,0,0] (對于每個索引,有一個包含 5 個獎牌的陣列,每個獎牌的權重從 0 到 4,0 是最不重要的,4 是最重要的.
填充陣列的示例:
[0] -> [0,17,0,0,2]
[1] -> [1,0,0,0,0]
[2] -> [0,12,39,21,0]
[3] -> [0,13,0,11,17]
我需要這樣的東西:
[1] -> [1,0,0,0,0]
[0] -> [0,17,0,0,2]
[3] -> [0,13,0,11,17]
[2] -> [0,12,39,21,0]
非常感謝。
uj5u.com熱心網友回復:
你可以使用sortedArrayWith它需要一個Comparator
多種選擇。
val medals = arrayOf(
arrayOf(0,17,0,0,2),
arrayOf(1,0,0,0,0),
arrayOf(0,12,39,21,0),
arrayOf(0,13,0,11,17)
)
val sorted = medals.sortedArrayWith { a1, a2 ->
a1.zip(a2)
.find { it.first != it.second }
?.let { it.second - it.first } ?: 0
}
或者
val sorted = medals.sortedArrayWith { a1, a2 ->
a1.zip(a2).forEach {
if(it.first != it.second) return@sortedArrayWith it.second-it.first
}
0
}
想法是找到計數不匹配的第一對/索引,并回傳最大值。
該解決方案是通用的,適用于任何大小的嵌套陣列
uj5u.com熱心網友回復:
如果我正確理解您的問題,您想按第一個、第二個、第三個等元素排序,然后按降序排列:
val list = arrayOf(
arrayOf(0, 17, 0, 0, 2),
arrayOf(1, 0, 0, 0, 0),
arrayOf(0, 12, 39, 21, 0),
arrayOf(0, 13, 0, 11, 17)
)
val result = list
.sortedArrayWith(
compareByDescending<Array<Int>> { it[0] }
.thenByDescending { it[1] }
.thenByDescending { it[2] }
.thenByDescending { it[3] }
.thenByDescending { it[4] }
)
result.forEach { println(it.toList()) }
uj5u.com熱心網友回復:
只是另一個快速通用的,不一定是最有效的!
// basically sorting in reverse order, so each pass allows a group
// to move to a 'better' position
val sorted = medalGroups.apply {
// assuming they all have the same number of indices
// you could check with require(all { it.size == first().size }) or something
for (i in first().indices.reversed()) {
sortByDescending { it[i] }
}
}
或者,如果您想避免重復,請解決 lukas.j 的答案(更好):
val sorted = medalGroups.sortedArrayWith(
// start with the basic index 0 comparator, and tack one on for every other index
(1 until list.size).fold(compareByDescending { it[0] }) { comparator, i ->
comparator.thenByDescending { it[i] }
}
)
您可以使用for回圈代替,但折疊很酷
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/489001.html
