blogscot
12/14/2018, 3:07 PMantonis
12/14/2018, 3:13 PMAlan Evans
12/14/2018, 3:14 PMfun countUpAndDownSequence(i: Int) =
(0 until i).asSequence() + (i downTo 0).asSequence()
blogscot
12/14/2018, 3:25 PMfun cycle(max: Int): Sequence<Int> =
sequence {
var step = 1
var output = 0
while (true) {
step *= when {
(output == max) and (step == 1) ||
(output == 0) and (step == -1) -> -1
else -> 1
}
yield(output)
output += step
}
}
but I imagined there was something bettercommanderpepper
12/14/2018, 3:29 PMcommanderpepper
12/14/2018, 3:29 PMfun countUpAndDownSequence(iterations: Int, max: Int): Sequence<Int> {
var sequence = emptySequence<Int>()
for (i in 0..iterations) {
sequence += (0 until max).asSequence() + (max downTo 0).asSequence()
}
return sequence
}
Alan Evans
12/14/2018, 4:50 PMAlan Evans
12/14/2018, 4:51 PMilya.gorbunov
12/14/2018, 4:54 PMfun countUpAndDownSequence(iterations: Int, max: Int) =
(0 until iterations * max * 2).asSequence()
.map { max - abs(max - it % (max * 2)) }
If you're not afraid some math 🙂
Though doesn't work with max = 0 well.commanderpepper
12/14/2018, 5:45 PMfun countUpAndDownSequence(iterations: Int, max: Int): Sequence<Int> {
var sequence = emptySequence<Int>()
for (i in 0 until iterations) {
when (i) {
0 -> sequence += (0 until max).asSequence() + (max downTo 0).asSequence()
else -> sequence += (1 until max).asSequence() + (max downTo 0).asSequence()
}
}
return sequence
}
commanderpepper
12/14/2018, 5:46 PMursus
12/16/2018, 12:34 AM