Title
r

reik.schatz

11/26/2018, 3:25 PM
given starting point
``val start = 0``
and
``listOf(3, 3, 3, 2)``
representing sizes of IntRange’s, whats the simplest way to turn this into a list of IntRanges? expected outcome
``listOf(IntRange(0, 2), IntRange(3, 5), IntRange(6, 8), IntRange(9, 10))``
d

diesieben07

11/26/2018, 3:34 PM
I'd just go for a straightforward for loop inside a generator sequence:
``````val start = 0
val list = listOf(3, 3, 3, 2)
val seq = sequence {
var curr = start
for (el in list) {
val next = curr + el
yield(curr until next)
curr = next
}
}``````
r

reik.schatz

11/26/2018, 3:39 PM
let me try this 🙂
j

Joris PZ

11/26/2018, 3:42 PM
My \$0.02:
``````val sizes = listOf(3, 3, 3, 2)
var start = 0
val ranges = sizes.map { size -> IntRange(start, start + size - 1).also {
start += size
}
}``````
d

diesieben07

11/26/2018, 3:42 PM
Personally not a fan of mutating state inside
``map``
and friends tbh
👆 3
j

Joris PZ

11/26/2018, 3:43 PM
Me neither
r

reik.schatz

11/26/2018, 3:47 PM
works, thanks guys
a

alex

11/26/2018, 4:23 PM
``````val start = 0
val list = listOf(3, 3, 3, 2)

val listNew = list.drop(1).fold(listOf(IntRange(start, list.first() - 1))) { acc, v ->
val r = acc.last().last
acc + listOf(IntRange(r + 1, r + v))
}
println(listNew)``````
But I'd recommend use simple for loop instead, since it's easier to read and understand
i

ilya.gorbunov

11/26/2018, 4:59 PM
Another functional (thus not very effective) approach:
``````val ranges = sizes
.fold(listOf(start)) { stops, length -> stops + (stops.last() + length) }
.zipWithNext { s, e -> s until e }``````
https://pl.kotl.in/SJrwLstRQ
r

reik.schatz

11/27/2018, 9:10 AM
wow, thanks for all suggestions