Home > Mobile >  How do we know which element is minimum in loop kotlin
How do we know which element is minimum in loop kotlin

Time:02-23

Hey I have list in kotlin. I am iterating over it. I want to store true/false as flag index which one is minimum value in whole list. I tried some code, but it's not working.

fun main() {
    val list = mutableListOf(4.83, 4.39, 3.58, 3.50, 3.46)
    val minValue = mutableListOf<BestMinimumValue>()
    var previousValue = 0.0

    list.forEach {
        minValue.add(BestMinimumValue(compareValue = previousValue > it))
        previousValue = it
    }
    minValue.forEach {
        println(it)
    }
}

data class BestMinimumValue(
    val compareValue: Boolean
)

Actual Output

BestMinimumValue(compareValue=false)
BestMinimumValue(compareValue=true)
BestMinimumValue(compareValue=true)
BestMinimumValue(compareValue=true)
BestMinimumValue(compareValue=true)

I'll explain what I need. In my list 3.46 is minimum value so on that place I need the flag as true and other one will be false.

Expected Output

BestMinimumValue(compareValue=false)
BestMinimumValue(compareValue=false)
BestMinimumValue(compareValue=false)
BestMinimumValue(compareValue=false)
BestMinimumValue(compareValue=true)

CodePudding user response:

It is not possible to create the resulting list while iterating, because we can't know if the current item is the smallest one or not. We have to iterate at least twice: first searching for the minimum value and then creating a resulting list.

One solution is to find the minimum and then compare items to it:

val min = list.minOrNull()!!
val minValue = list.map { BestMinimumValue(it == min) }

Note if there are multiple same minimum values, then all of them will be marked as true.

If this is not expected behavior or if we like to avoid comparing items twice, then we can find the index of the minimum value and just construct the resulting list with it:

val minIndex = list.withIndex().minByOrNull { it.value }!!.index
val minValue = List(list.size) { BestMinimumValue(it == minIndex) }
  • Related