Laba Diena
Laba Diena

Reputation: 87

How to sort two arrays in the same way but leave unsortable elements in their places?

I use this code to do that:

var letters = arrayOf("one", "two", "three")
    var digits = arrayOf(2.36, 1.1, 3.0)

    val x = digits.zip(letters).toMap().toSortedMap { o1, o2 -> o2.compareTo(o1)}
    val keys = x.keys.toList()        // [3.0, 2.36, 1.1]
    val values = x.values.toList()    // [three, one, two]

But noticed one thing which is not very good. If array of digits contains more than one the same element, only the last of them is visible in keys. Is there any way to put all the same elements and leave letters elements in it's places in such case? For example: if there is [3.0, 2.36, 1.1, 1.1] in array. This code turns it to [3.0, 2.36, 1.1]. How can I solve this problem?

Upvotes: 0

Views: 126

Answers (1)

broot
broot

Reputation: 28312

You should not convert it to a map. Map is a data structure where keys are unique and you don't really use any features of the map here.

You can do this with the following code:

val lettersSorted = digits.zip(letters)
    .sortedByDescending { it.first }
    .map { it.second }

I'm not sure if you need a sorted list of letters only or both. And if both then whether you prefer to keep them in separate lists or in a single list. You can acquire all of these lists like this:

val sorted = digits.zip(letters)
    .sortedByDescending { it.first }  // sorted list of digits and letters

val sortedDigits = sorted.map { it.first }
val sortedLetters = sorted.map { it.second }

Upvotes: 3

Related Questions