Multidimensional Arrays and Their Traversal in Kotlin

Topic Overview

Welcome to today's session on "Multidimensional Arrays and Their Traversal in Kotlin". Multidimensional arrays in Kotlin are arrays that can hold other arrays as their elements. Imagine them as an 'apartment building' with floors (the outer array) and apartments on each floor (the inner array). Our goal today is to strengthen your foundational knowledge of these 'apartment buildings' and how to handle them effectively in Kotlin.

Creating Multidimensional Arrays

In Kotlin, we use arrays of arrays to construct a multidimensional array. Here are examples demonstrating how to create and work with 2D static arrays.

fun main() {
    // Creating a 2D array
    val array = arrayOf(
        arrayOf(1, 2, 3),
        arrayOf(4, 5, 6),
        arrayOf(7, 8, 9)
    )

    println(array.contentDeepToString()) // Outputs [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
}

Indexing in Multidimensional Arrays

In Kotlin, all indices in arrays are 0-based. If you want to visit an apartment on the second floor (index 1) and bring a package to the first unit (index 0) in this building, you would do:

fun main() {
    val array = arrayOf(
        arrayOf(1, 2, 3),
        arrayOf(4, 5, 6),
        arrayOf(7, 8, 9)
    )

    // Accessing an element
    println(array[1][0])  // Outputs: 4
}

We accessed the element 4 in the array using its position. The number [1] refers to the second inner array, and [0] refers to the first element of that array.

Traversing Multidimensional Arrays

In Kotlin, you can visit every floor (outer array) and every apartment on each floor (inner array) using nested loops.

fun main() {
    val array = arrayOf(
        arrayOf("Apt 101", "Apt 102", "Apt 103"),
        arrayOf("Apt 201", "Exit Floor", "Apt 203"),
        arrayOf("Apt 301", "Apt 302", "Apt 303")
    )

    // Loop through 2D array
    for (floor in array) {
        for (apartment in floor) {
            print("$apartment, ")
        }
        println()
    }
    /*
    Expected output:
    Apt 101, Apt 102, Apt 103, 
    Apt 201, Exit Floor, Apt 203, 
    Apt 301, Apt 302, Apt 303, 
    */
}

Updating Multidimensional Arrays

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal