TwoClocks
11/28/2020, 10:34 PM[-1,-1,-1,1,1,-1,-1]
should yield [-3,2,-2]
I can't figure out how to do this w/o iterating over the list, and keeping a bunch of mutable state. Is there fancy sequence of collection functions I could use to do this?ephemient
11/28/2020, 11:38 PMByron Katz
11/29/2020, 4:22 AMAstronaut4449
11/29/2020, 11:22 PMfun List<Int>.accumulatedSigns(): List<Int> = sequence {
var tempSum = first()
for (element in asSequence().drop(1)) {
if(element.sign == tempSum.sign) {
tempSum += element
} else {
yield(tempSum)
tempSum = element
}
}
yield(tempSum)
}.toList()
ephemient
11/30/2020, 5:36 AMTwoClocks
11/30/2020, 8:26 AMrunningReduce
is a new one for me....TwoClocks
11/30/2020, 8:26 AMTwoClocks
11/30/2020, 8:27 AMTwoClocks
11/30/2020, 8:27 AMAstronaut4449
11/30/2020, 9:15 AMAstronaut4449
11/30/2020, 9:44 AMTwoClocks
11/30/2020, 9:13 PMephemient
11/30/2020, 9:25 PMTwoClocks
11/30/2020, 9:47 PMTwoClocks
11/30/2020, 9:48 PMByron Katz
11/30/2020, 9:49 PMByron Katz
11/30/2020, 9:51 PMTwoClocks
11/30/2020, 9:53 PMTwoClocks
11/30/2020, 9:54 PMTwoClocks
11/30/2020, 9:55 PMmapWithState
where the state itself doesn't end up part of the resulting list.ephemient
11/30/2020, 9:56 PM.reduce()
and its more general cousin .fold()
(and the variants .runningReduce()
and .runningFold()
(with alias .scan()
)) carry over one piece of state as they iterate over each elementTwoClocks
11/30/2020, 9:58 PMephemient
11/30/2020, 9:59 PMTwoClocks
11/30/2020, 10:00 PMTwoClocks
11/30/2020, 10:00 PMephemient
11/30/2020, 10:00 PMTwoClocks
11/30/2020, 10:01 PMephemient
11/30/2020, 10:03 PMephemient
11/30/2020, 10:04 PMSet
as an accumulator, but adding to it will make the whole operation O(n^2) so that's not goodTwoClocks
11/30/2020, 10:04 PMephemient
11/30/2020, 10:06 PMTwoClocks
11/30/2020, 11:02 PMsequence {
I'm not quite sure what this
has all in it 🙂Val Salamakha
12/01/2020, 3:13 AM@ExperimentalStdlibApi
fun Iterable<Int>.accumulatedSigns(): List<Int> = buildList {
val iterator = this@accumulatedSigns.iterator()
println("iterator ${iterator.hasNext()}")
if (!iterator.hasNext())
return@buildList
var sum = iterator.next()
for (x in iterator) {
if (x.sign != sum.sign) {
add(sum)
sum = x
} else {
sum += x
}
}
add(sum)
}