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.
Simon Lin
10/19/2020, 6:50 AM
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
Petter Måhlén
10/19/2020, 6:53 AM
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
kioba
10/19/2020, 7:45 AM
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
kioba
10/19/2020, 7:49 AM
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.