Home > Blockchain >  Find the list item of Pairs with the minimum value
Find the list item of Pairs with the minimum value

Time:12-25

val index = listOf("abc", "def", "ghi", "jkl", "mno")
    .mapIndexed { index, v ->
        var t = 0
        var p = 0
        for (s in v) {
            t  = ("deh".get(p  ).toInt() - s.toInt()).absoluteValue
        }
        Pair(index, v)
    }
    .minOf {
        val iterator = iterator<Pair<Int, String>>(it)
        if (!iterator.hasNext()) throw NoSuchElementException()
        var minValue = iterator.next().second
        while (iterator.hasNext()) {
            val v = selector(iterator.next())
            minValue = minOf(minValue, v)
        }
        return minValue
    }

This is an alternative solution and works, but I am wondering if the solution can be done using mapOf as shown above?

val index = listOf("abc", "def", "ghi", "jkl", "jad", "jaa", "mno")
    .mapIndexed { index, v ->
        var t = 0
        var p = 0
        for (s in v) {
            t  = ("jac".get(p  ).toInt() - s.toInt()).absoluteValue
        }
        Pair(index, t)
    }.toSortedSet(compareBy { it.second })
    .first()

I create a map of Pairs and I want to find the index of the map item where the Pair with the value (the second item in the pair) is the lowest value (minimum) of all the pairs. If possible, I would like to use the minOf function. The first example above will not compile because of bugs in the minOf function. Not sure how to iterate over the map of Pairs.

CodePudding user response:

You can use minBy {} to get the minimum value from a collection, although often it's safer to use minByOrNull {} in case no minimal value can be computed (which could happen if the list is empty).

import kotlin.math.absoluteValue

fun main() {
  val minElement = listOf("abc", "def", "ghi", "jkl", "jad", "jaa", "mno")
    .minByOrNull { v ->
      var t = 0
      var p = 0
      for (s in v) {
        t  = ("jac".get(p  ).toInt() - s.toInt()).absoluteValue
      }
      t
    }
  println(minElement)
}
jad

Run in Kotlin Playground

If you also want to find the index of the minimal value, then you can use withIndex(), which will pair each list element with its index.

import kotlin.math.absoluteValue

fun main() {
  val minIndexedElement = listOf("abc", "def", "ghi", "jkl", "jad", "jaa", "mno")
    .withIndex() // adds the index to each element 
    .minByOrNull { (_, v) ->
      var t = 0
      var p = 0
      for (s in v) {
        t  = ("jac".get(p  ).toInt() - s.toInt()).absoluteValue
      }
      t
    }
  println(minIndexedElement)
}
IndexedValue(index=4, value=jad)

Run in Kotlin Playground

  • Related