Menu
Coddy logo textTech

Lists of Lists

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 16 of 63.

A nested list stores rows as elements of an outer list. The outer size counts rows; each inner size counts that row's elements. Use two indices to select one value, and keep both within their own bounds.

Inside main:

val grid = listOf(listOf(2, 4), listOf(6, 8))
println(grid[1][0])

Index one chooses the second row, then index zero chooses its first value.

The first index selects a row and the second selects an element of that row.

challenge icon

Challenge

Medium

Complete cellAt with parameters grid: List<List<Int>>, row: Int, column: Int. Return the selected cell. The supplied row and column are always valid for that row.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type Int. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun cellAt(grid: List<List<Int>>, row: Int, column: Int): Int {
    // Write your solution here.
    return 0
}
fun main() {
    val gridCount = readln().toInt()
    val grid = mutableListOf<List<Int>>()
    for (i0 in 0 until gridCount) {
        val gridItemCount = readln().toInt()
        val gridItem = mutableListOf<Int>()
        for (i1 in 0 until gridItemCount) {
            val gridItemItem = readln().toInt()
            gridItem.add(gridItemItem)
        }
        grid.add(gridItem)
    }
    val row = readln().toInt()
    val column = readln().toInt()
    println(cellAt(grid, row, column))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground