Ian Rehwinkel
Ian Rehwinkel

Reputation: 2615

Turn a list into a distinct list and map indices

I have a List of Objects, and I want to turn it into a distinct list while mapping all indices to the new indices.

Example:

List: ["a", "b", "a", "d"] -> ["a", "b", "d"]

Map:

{
  0: 0, //0th index of original list is now 0th index of distinct list
  1: 1,
  2: 0, //2nd index of original list is now 0th index of distinct list
  3: 2  //3rd index of original list is now 2th index of distinct list
} 

Is there a simple way to do this with a one-liner or with a fairly simple solution in kotlin?

Upvotes: 2

Views: 5410

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81929

I think this would solve the problem pretty neatly:

val orig = listOf("a", "b", "a", "c")

val positions = orig.distinct().let { uniques ->
    orig.withIndex().associate { (idx, e) -> idx to uniques.indexOf(e) }
}

Upvotes: 2

Eugene Petrenko
Eugene Petrenko

Reputation: 4992

The following expression will do that:

val p = listOf("a", "b", "a", "d").let {
  val set = it.distinct().mapIndexed { i, v -> v to i }.toMap()
  it.mapIndexed { i, v -> i to set.getValue(v) }
}.toMap()

Upvotes: 4

Related Questions