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--
    }
4

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

does chunked() not work with arrays?. I thought vararg gives a parameter the qualities of an array.
Updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.