I'm working for a school project and i need to sort a multidimensional array using Kotlin. The array contains arrays of medals. I need to sort it like a medal table, where depending on the medal weight and medals count.
The array is something like this:
[0] -> [0,0,0,0,0] (for each index there is an array of 5 medals, each medal has a weight from 0 to 4, 0 is the is the least important, 4 is the most.
Example of populated array:
[0] -> [0,17,0,0,2]
[1] -> [1,0,0,0,0]
[2] -> [0,12,39,21,0]
[3] -> [0,13,0,11,17]
I need something like this:
[1] -> [1,0,0,0,0]
[0] -> [0,17,0,0,2]
[3] -> [0,13,0,11,17]
[2] -> [0,12,39,21,0]
Thank you very much.
CodePudding user response:
You can use sortedArrayWith
that takes a Comparator
Multiple options.
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
}
or
val sorted = medals.sortedArrayWith { a1, a2 ->
a1.zip(a2).forEach {
if(it.first != it.second) return@sortedArrayWith it.second-it.first
}
0
}
Idea is to find the first pair/index where the counts don't match, and return the maximum value.
The solution is generic that would work with any size of nested array
CodePudding user response:
If I understand your question correctly, you want to sort by the first, then the second, then the third, etc. element, and that in descending order:
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()) }