How to split a list to sub list with random size? ...
# announcements
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]
[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)
Is there better way?
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
You could use slice, calculate the random ranges and apply slice. This might help you choose: 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.
functional, not necessarily better.
but this would work on all iterables and sequences, not just lists