'The most efficient solution for finding the minimum value
I have a list of Sugar. The Sugar class has two field: price and weight:
data class Sugar(var price: Double, var weight: Double)
And I need to find max/min value by this fields. I found two ways to do this. The first way is to use a ready-made solution:
val minPrice = list.minBy { it.price }?.price
val maxPrice = list.maxBy { it.price }?.price
val minWeight = list.minBy { it.weight }?.weight
val maxWeight = list.maxBy { it.weight }?.weight
Second way:
var minPrice = list.first().price
var maxPrice = list.first().price
var minWeight = list.first().weight
var maxWeight = list.first().weight
for (i in 1..list.size) {
if (list[i].price < minPrice) {
minPrice = list[i].price
}
if (list[i].price > maxPrice) {
maxPrice = list[i].price
}
if (list[i].weight < minWeight) {
minWeight = list[i].weight
}
if (list[i].weight > maxWeight) {
maxWeight = list[i].weight
}
}
Both solutions work, but I need to find the most efficient one. Please, tell me which method is better to use, or perhaps there is a more efficient solution for this purpose.
Solution 1:[1]
Obviously the first solution iterates over the list for four times, while the second one iterates only once. So second option is performant. You can rewrite the solution in functional way
data class Metrics(val minPrice: Double = 0.0, val maxPrice: Double = 0.0, val minWeight: Double = 0.0, val maxWeight: Double = 0.0)
val (minPrice, maxPrice, minWeight, maxWeight) = list.fold(Metrics()){ acc, sugar ->
Metrics(
minPrice = min(sugar.price, acc.minPrice),
maxPrice = max(sugar.price, acc.maxPrice),
minWeight = min(sugar.weight, acc.minWeight),
maxWeight = max(sugar.weight, acc.maxWeight)
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sidgate |