How to reconstruct a full sparse matrix from a compact (triplet) matrix in Kotlin

1 Answer

0 votes
object RebuildSparseMatrix {

    // A sparse matrix is a matrix in which the majority of elements are zero.

    // To rebuild a sparse matrix from a compact (triplet) representation,
    // We create a full matrix initialized with zeros, then place each
    // non‑zero element at its (row, column) position.

    // Build a full sparse matrix from compact triplet form
    fun buildSparseFromCompact(compact: Array<IntArray>, count: Int): Array<IntArray> {

        val rowIdx = compact[0]
        val colIdx = compact[1]
        val values = compact[2]

        // Determine matrix dimensions automatically
        var maxRow = 0
        var maxCol = 0

        for (i in 0 until count) {
            if (rowIdx[i] > maxRow) maxRow = rowIdx[i]
            if (colIdx[i] > maxCol) maxCol = colIdx[i]
        }

        val rows = maxRow + 1
        val cols = maxCol + 1

        // Create full matrix initialized with zeros
        val sparse = Array(rows) { IntArray(cols) }

        // Fill matrix
        for (i in 0 until count) {
            sparse[rowIdx[i]][colIdx[i]] = values[i]
        }

        return sparse
    }

    // Print a matrix
    fun printMatrix(mat: Array<IntArray>, title: String) {
        println(title)
        for (row in mat) {
            println(row.joinToString(" "))
        }
        println()
    }

    @JvmStatic
    fun main(args: Array<String>) {

        // Compact matrix:
        // 0 0 1 1 1 3 3 3 4
        // 2 4 2 3 6 1 2 5 4
        // 3 8 5 7 1 2 6 4 9

        val compact = arrayOf(
            intArrayOf(0, 0, 1, 1, 1, 3, 3, 3, 4),  // row indices
            intArrayOf(2, 4, 2, 3, 6, 1, 2, 5, 4),  // column indices
            intArrayOf(3, 8, 5, 7, 1, 2, 6, 4, 9)   // values
        )

        val count = 9

        println("Compact matrix:")
        for (i in 0 until 3) {
            println((0 until count).joinToString(" ") { compact[i][it].toString() })
        }
        println()

        val sparse = buildSparseFromCompact(compact, count)

        printMatrix(sparse, "Sparse matrix (auto-sized):")
    }
}


/*
run:

Compact matrix:
0 0 1 1 1 3 3 3 4
2 4 2 3 6 1 2 5 4
3 8 5 7 1 2 6 4 9

Sparse matrix (auto-sized):
0 0 3 0 8 0 0
0 0 5 7 0 0 1
0 0 0 0 0 0 0
0 2 6 0 0 4 0
0 0 0 0 9 0 0

*/

 



answered 3 hours ago by avibootz

Related questions

...