我有个kotlin问题,你能想出一个很好的解决方法吗?
因此,实际上,我有一份可以乘车或不坐的旅行清单,我想找出清单中是否有连续的汽车行程,即名单中有2辆或2辆以上的汽车。然后,从这些连续的汽车链,我想总结每一个链的里程,并打印出最大。这是数据类。
data class Journey(
val isCar: Boolean = false,
val mileage: Int,
)下面是一个旅行清单。因此,在这个例子中,正确的答案应该是80,因为有两个连续的条目,以40+40作为里程。这比10+20=30的其他唯一连续条目要好。剩下的是单车径和非车程,所以被忽略了。
listOf(
Journey(true, 10),
Journey(true, 20),
Journey(false, 105),
Journey(true, 1046),
Journey(false, 130),
Journey(true, 40),
Journey(true, 40),
)我的解决方案如下,但它是非常丑陋和非功能性的。您能以一种优雅的方式解决这个问题,使用现代功能技术而不需要可变的列表吗?谢谢
val journeys = listOf(
Journey(true, 10),
Journey(true, 20),
Journey(false, 105),
Journey(true, 1046),
Journey(false, 130),
Journey(true, 40),
Journey(true, 40),
)
val cars = journeys.filter { it.isCar }
val journeysByIndex = cars.map { journeys.indexOf(it) to it }
val consecutiveJourneys = mutableListOf<MutableList<Journey>>()
journeysByIndex.forEach {
if (consecutiveJourneys.any { cj1 -> cj1.any { cj2 -> cj2 == it.second } }) {
return@forEach
}
val journeyList = mutableListOf(it.second)
var index = it.first
var nextJourneyExists = true
while (nextJourneyExists) {
var journey: Journey? = null
if ((index + 1) < journeys.size && journeys[index + 1].isCar) {
journey = journeys[index+1]
}
nextJourneyExists = if (journey!= null) {
journeyList.add(journey)
true
} else {
false
}
index += 1
}
consecutiveJourneys.add(journeyList)
}
var maxAmountForConsecutive = consecutiveJourneys.filter {it.size > 1 }.map{ it.sumOf {cs -> cs.mileage}}.max()
println("max1: " + maxAmountForConsecutive)发布于 2022-11-26 01:15:14
除了Tenfour04在注释中建议的分组方法(我个人觉得这样的任务有点过分了)(但它在其他场景中很有用)之外,您也可以简单地计算一下。
我们可以创建一个简单的扩展函数来计数每一步,然后一旦它到达isCar:false就重新设置。
fun Collection<Journey>.calculateMaxByCarConsecutive(): Int {
var max = 0
var currentMileageSum = 0
var count = 0
forEach { current ->
if (current.isCar) {
//if the current journey is in a car, add its mileage to our current count
currentMileageSum += current.mileage
//increase count that tells us how many journeys have been consecutive
count++
//if we have more than 1 journey creating the currentMileageSum
//and
//currentMileageSum is greater than max,
// then the currentMileageSum becomes the new max
if (count > 1) max = maxOf(currentMileageSum, max)
} else {
//reset the counters if this record is not by car
count = 0
currentMileageSum = 0
}
}
return max
}然后我们就可以这样称呼它:
val journeys = listOf(
Journey(true, 10),
Journey(true, 20),
Journey(true, 40),
Journey(false, 105),
Journey(true, 10423423),
Journey(false, 130),
Journey(true, 40),
Journey(true, 40),
Journey(true, 10),
)
val maxJourneyByCar = journeys.calculateMaxByCarConsecutive()
println(maxJourneyByCar) //this will print 90不确定这是否比您的解决方案更优雅,或者比使用折叠更优雅,但我确实认为它更简单。
https://stackoverflow.com/questions/74578931
复制相似问题