How to split a list to sub list with random size? ...
# announcements
s
How to split a list to sub list with random size? input:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
and random sub list size range from 0 to 4. output:
[0, 1]
[2, 3, 4, 5]
[6]
[]
[7, 8]
[]
[9, 10]
Each sub list size is random.
This is my way:
Copy code
while (list.isNotEmpty()) {
    val size = (0..4).random()
    val sublist = list.subList(0, size)
    result.add(sublist)
    list.removeAll(sublist)
}
Is there better way?
p
IMO, any way that works and is relatively readable is fine 🙂 you could go more functional and generate an infinite sequence of random ints in 0..4, and then take things from the input list until it ends, but there’s no guarantee that that’ll be more maintainable
🙆‍♂️ 1
k
You could use slice, calculate the random ranges and apply slice. This might help you choose: https://kotlinlang.org/docs/reference/collection-parts.html To make it FPish create a higher kind function which receives the remaining list and returns always the next slice.
👍 1
Simon you can optimise your solution by not removing the elements, instead memo the sublist start index and use that in the sublist as the start index instead of null. Not sure about the list implementation but probably it shifts the remaining elements if you remove from the start of the array.
e
functional, not necessarily better. https://pl.kotl.in/34GD7Zhvf
but this would work on all iterables and sequences, not just lists