Matrix Manipulation: Combining Submatrices in Go

Introduction

Welcome, Go enthusiast! This lesson guides you through the exciting world of matrix manipulation using Go. You'll combine submatrices from two distinct matrices to create a new one. While this task might seem complex at first, we'll break it down step by step. By the end of this lesson, you'll have mastered the handling of matrices in Go.

Task Statement

Ready for the challenge? Picture having two different 2D slices, A and B. Our task is to develop a Go function — let's call it SubmatrixConcatenation() — which takes these two slices as inputs, along with coordinates specifying submatrices within A and B. This function should merge the chosen submatrices into a new one, C. The submatrices from A and B must have the same number of rows. In C, elements from A's submatrix should be on the left, and those from B on the right.

Consider matrix A:

[[1, 2, 3, 4],
 [5, 6, 7, 8],
 [9, 10, 11, 12]]

and matrix B:

[[11, 12, 13],
 [14, 15, 16],
 [17, 18, 19]]

If we select 2x2 submatrices (using the 2nd-3rd rows and 2nd-3rd columns from A and 1st-2nd rows and 1st-2nd columns from B), their concatenation would be:

[[6, 7, 11, 12],
 [10, 11, 14, 15]]

Extracting and Combining Rows

To solve this problem, we can simply directly extract and combine the rows from matrices A and B based on the given coordinates. Here's how you can do it:

package main

import (
    "fmt"
)

func SubmatrixConcatenation(matrixA, matrixB [][]int, submatrixCoords [2][4]int) [][]int {
    startRowA, endRowA := submatrixCoords[0][0]-1, submatrixCoords[0][1]-1
    startColA, endColA := submatrixCoords[0][2]-1, submatrixCoords[0][3]-1
    startRowB := submatrixCoords[1][0]-1, submatrixCoords[1][1]-1
    startColB, endColB := submatrixCoords[1][2]-1, submatrixCoords[1][3]-1

    numRows := endRowA - startRowA + 1

    resultMatrix := make([][]int, numRows)
    for i := 0; i < numRows; i++ {
        rowA := matrixA[startRowA+i][startColA : endColA+1]
        rowB := matrixB[startRowB+i][startColB : endColB+1]
        resultMatrix[i] = append(rowA, rowB...)
    }

    return resultMatrix
}

func PrintMatrix(matrix [][]int) {
    for _, row := range matrix {
        fmt.Println(row)
    }
}

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

    matrixB := [][]int{
        {11, 12, 13},
        {14, 15, 16},
        {17, 18, 19},
    }

    submatrixCoords := [2][4]int{
        {2, 3, 2, 3},
        {1, 2, 1, 2},
    }

    result := SubmatrixConcatenation(matrixA, matrixB, submatrixCoords)
    PrintMatrix(result)
}
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