Edit:
I had to return a set of passengers who had majority of discounts. The solution to this riddle was as following,
- Extract all the passengers count in a Map
- Extract all the passengers count in a Map who received discounts.
- Then in a loop I had to apply a lambda to find percentage and see if which passengers received discount on majority of the trips.
- Add them to a set and return it.
Please see the code below,
fun findDiscountedPassengers(): Set<Passenger> {
var discountedPassengerList: MutableList<Passenger> = emptyList<Passenger>().toMutableList()
var passengerTripCountMap = trips.flatMap { it.passengers }.groupingBy { it }.eachCount()
var passengerDiscountedTripsMap = trips.filter { it.discount != null }
.flatMap { it: Trip -> it.passengers }
.groupingBy { it }
.eachCount()
val findPercentage = ...
passengerDiscountedTripsMap.forEach { it: Map.Entry<Passenger, Int> ->
val totalTripsCount: Double? = passengerTripCountMap.get(it.key)?.toDouble()
if (findPercentage(it.value.toDouble(), totalTripsCount?:0.0) > majorPercentage) {
discountedPassengerList.add(it.key)
}
}
return discountedPassengerList.toSet()
}
My code seems a bit more Java-ish than Kotlin since its not that concise/short or optimized. I created two different groups resulting in two Maps; then create a loop to apply rest of the logic. I think allot of the unnecessary steps can be removed.
Example: Conversion of list to set to return the result and so on.
How can I avoid creating two groups resulting in two different maps? What optimizations can I apply from steps 1 to 4? Can I leverage Partition (not sure about the concept) in any way to reduce the number of steps I have taken in the code above?
Thanks.