1

Given a maximum list size in parameter size and total amount of elements in parameter elements, I need to create a list of lists. What is the syntax for creating variables in for loops in Kotlin?

The way I'm thinking of going about this is to declare and create lists before elements are added to a list. Then, when a list has reached full capacity, it is switched out for the next list that is empty.

Here is the half-baked code:

fun listOfLists(size: Int, vararg elements: String): List<List<String>> {
    var amountOfElements = elements.size
    var currentSubList: List<String> = mutableListOf<String>()
    val numberOfLists: Int = amountOfElements / size + 1

    for (n in 0..numberOfLists) {
        // Code for creating the total number of lists needed
    }

    for (e in elements) {
        if (amountOfElements % size == 0) {
            // Code for switching lists
        }
        amountOfElements--
    }
ordonezalex
  • 2,645
  • 1
  • 20
  • 33
Jisip
  • 415
  • 3
  • 14
  • 1
    Is it what you need? https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/chunked.html. The implementation is here, if you are interested: https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt. –  Jun 27 '19 at 21:01
  • @dyukha Thank you – Jisip Jun 27 '19 at 21:17
  • Possible duplicate of [Divide list into parts](https://stackoverflow.com/questions/40699007/divide-list-into-parts) – ordonezalex Jun 28 '19 at 08:04
  • The answer and comments helped me to implement but don't actually answer the question. – Jisip Jun 28 '19 at 17:53

1 Answers1

2

As @dyukha correctly mentioned, what you need is chunked() function.

fun listOfLists(size: Int, vararg elements: String) = 
   elements.asList().chunked(size)

Or, if you want to be really efficient, you can also use asSequence():

fun listOfLists(size: Int, vararg elements: String) =
    elements.asSequence().chunked(size)

chunked() doesn't work on Array, because it's defined on Iterable and Sequence, and Array doesn't implement any of them.

Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40