Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i sort a medal table array in Kotlin?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading