Matrix Manipulation and Submatrix Concatenation in Kotlin

Introduction

Hello Coder! In this unit's engaging programming lesson, we're going to traverse the world of two-dimensional matrices using Kotlin. We'll leverage Kotlin's concise and expressive syntax to combine submatrices from two different matrices into a new one. This might sound challenging at first, but with Kotlin's powerful features, we'll tackle it efficiently, step by step.

Task Statement

Are you ready for the task? Here it is: Imagine having two different 2D arrays, A and B. Our job is to devise a Kotlin function — let's name it submatrixConcatenation — which takes these two matrices as inputs, along with the coordinates specifying submatrices within A and B. This function will stitch the two chosen submatrices together to form a new one, C. The submatrices from A and B should have the same number of rows, and in the final matrix C, elements from A's submatrix should appear on the left and those from B's submatrix should be on the right.

Let's visualize this with a couple of matrices.
Given the matrix A as:

{{1, 2, 3, 4},
 {5, 6, 7, 8},
 {9, 10, 11, 12}}

and the matrix B as:

{{11, 12, 13},
 {14, 15, 16},
 {17, 18, 19}}

If we select 2x2 submatrices from each (comprising the 2nd to 3rd rows and 2nd to 3rd columns from A, and 1st to 2nd rows and 1st to 2nd columns from B), their concatenation would look like:

{{6, 7, 11, 12},
 {10, 11, 14, 15}}

Solution Building: Step 1

Our first step toward the solution is to extract submatrices from A and B from the given coordinates. For this, we'll use Kotlin's loop constructs and array slicing abilities:

fun submatrixConcatenation(
    matrixA: Array<IntArray>,
    matrixB: Array<IntArray>,
    submatrixCoords: Array<IntArray>
): Array<IntArray> {

    val (startRowA, endRowA, startColA, endColA) = submatrixCoords[0]
    val (startRowB, endRowB, startColB, endColB) = submatrixCoords[1]

    val numRows = endRowA - startRowA + 1
    val numColsA = endColA - startColA + 1
    val numColsB = endColB - startColB + 1

    val submatrixA = Array(numRows) { row ->
        IntArray(numColsA) { col ->
            matrixA[startRowA + row - 1][startColA + col - 1]
        }
    }

    val submatrixB = Array(numRows) { row ->
        IntArray(numColsB) { col ->
            matrixB[startRowB + row - 1][startColB + col - 1]
        }
    }
    
    // At this point, we have extracted submatrices from matrixA and matrixB
    return submatrixA // This is temporary. We'll continue in step 2.
}
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