Topic Overview

Welcome to today's session on "Mastering Array Traversal and Manipulation in Go". Multidimensional arrays in Go are like an 'apartment building' with floors (the outer array) and apartments on each floor (the inner array). Today, our goal is to enhance your understanding of these 'apartment buildings' and how to effectively manage them using Go's syntax and data structures.

Creating Multidimensional Arrays

In Go, we create a multidimensional array by defining arrays containing arrays. Let's see how to create and work with 2D arrays.

package main

import "fmt"

func main() {
    // Creating a 2D array
    array := [3][3]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }

    // Printing the 2D array
    for i := 0; i < len(array); i++ {
        for j := 0; j < len(array[i]); j++ {
            fmt.Print(array[i][j], " ")
        }
        fmt.Println()
    }
}

/*
Prints:
1 2 3 
4 5 6 
7 8 9 
*/
Indexing in Multidimensional Arrays

Indices in Go arrays, like in many programming languages, are 0-based. To access a specific element, we specify the indices. For example, visiting the apartment on the second floor (index 1) and delivering a package to the first unit (index 0):

package main

import "fmt"

func main() {
    array := [3][3]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }

    // Accessing an element
    fmt.Println(array[1][0]) // Outputs: 4
}

We've accessed the element 4 in the array by its row and column indices.

Finding the Number of Rows and Columns

In Go, to determine the number of rows (floors) and columns (apartments per floor), we use the len function, which returns the length of an array dimension.

package main

import "fmt"

func main() {
    array := [3][3]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }

    // Finding the number of rows
    numFloors := len(array)
    fmt.Println(numFloors)  // Outputs: 3

    // Finding the number of columns
    numUnits := len(array[0])
    fmt.Println(numUnits)  // Outputs: 3
}
Traversing Multidimensional Arrays

To visit each floor (outer array) and each apartment on each floor (inner array), we use nested loops.

package main

import "fmt"

func main() {
    array := [3][3]string{
        {"Apt 101", "Apt 102", "Apt 103"},
        {"Apt 201", "Exit Floor", "Apt 203"},
        {"Apt 301", "Apt 302", "Apt 303"},
    }

    // Loop through the 2D array
    for i := 0; i < len(array); i++ {
        for j := 0; j < len(array[i]); j++ {
            fmt.Print(array[i][j], ", ")
        }
        fmt.Println()
    }
}

/*
Prints:
Apt 101, Apt 102, Apt 103,
Apt 201, Exit Floor, Apt 203,
Apt 301, Apt 302, Apt 303,
*/
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