Paulo Cereda
12/13/2024, 10:24 PMsleepsort
in Kotlin. 😁 The best I could come up with is as follows (playground link):
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
suspend fun main() {
println(sleepsort(listOf(63, 32, 62, 14, 5)))
}
suspend fun sleepsort(list: List<Int>): List<Int> = coroutineScope {
buildList {
list.map { number ->
async {
delay(number.toLong())
add(number)
}
}.awaitAll()
}
}
Do you have any suggestions and/or improvements to make it better (or even worse)? Thank you so much, and season's greetings to everyone! 🎄Joffrey
12/13/2024, 10:39 PMlaunch
instead. Then you also don't need awaitAll()
(or rather joinAll()
once you replaced async
with launch
), because coroutineScope
will wait for it's children. You will have to move it inside buildList
though.Paulo Cereda
12/13/2024, 11:05 PMJoffrey
12/13/2024, 11:41 PMRobert Williams
12/17/2024, 1:33 PMsuspend fun sleepsort(list: List<Int>): List<Int> =
list.asFlow().map { number ->
flow {
delay(number.toLong())
emit(number)
}
}.flattenMerge(list.size).toList()