Is there an nice way to generate a sequence like 0...
# getting-started
b
Is there an nice way to generate a sequence like 0 1 2 3 2 1 0 …?
a
Copy code
fun countUpAndDownSequence(i: Int) =
        (0 until i).asSequence() + (i downTo 0).asSequence()
👍 4
b
I came up with
Copy code
fun 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 better
c
Using Alan's code I came up with
Copy code
fun 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
}
a
did you run it?
got bugs, `0`s are repeated, and an out by one error on the number iterations.
i
Copy code
fun 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.
c
Copy code
fun 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
}
I think that code works
u
cycle?