'is there any method to split list of string to list of string where each sublist's sum of elements size less than N? [closed]
I want to convert following list
["abcd", "abcd", "abcd", "abcd", "abcd", "a"]
to this list
[["abcd", "abcd"], ["abcd", "abcd"], ["abcd", "abcd", "a"]]
the sum of the lengths of the sublist elements must be less than 10
in other words i want to add string into sublist while it sum of size of elements less than 10
Here's my attempt
val list = listOf("abcd", "abcd", "abcd", "abcd", "abcd", "abcd", "a")
var currentGroupSize = 0
var sublist = mutableListOf<String>()
var result = mutableListOf<List<String>>()
for (element in list) {
if (element.length + currentGroupSize < 10) {
sublist.add(element)
currentGroupSize += element.length
} else {
result.add(sublist)
sublist = mutableListOf(element)
currentGroupSize = element.length
}
}
println(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
