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

1 Answer

0 votes
package main

import (
    "fmt"
)

// 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 full sparse matrix from compact triplet form
func buildSparseFromCompact(compact [][]int, count int) [][]int {

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

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

    for i := 0; i < count; i++ {
        if rowIdx[i] > maxRow {
            maxRow = rowIdx[i]
        }
        if colIdx[i] > maxCol {
            maxCol = colIdx[i]
        }
    }

    rows := maxRow + 1
    cols := maxCol + 1

    // Create full matrix initialized with zeros
    sparse := make([][]int, rows)
    for i := range sparse {
        sparse[i] = make([]int, cols)
    }

    // Fill matrix
    for i := 0; i < count; i++ {
        sparse[rowIdx[i]][colIdx[i]] = values[i]
    }

    return sparse
}

// Print a matrix
func printMatrix(mat [][]int, title string) {
    fmt.Println(title)
    for _, row := range mat {
        for _, x := range row {
            fmt.Printf("%d ", x)
        }
        fmt.Println()
    }
    fmt.Println()
}

func main() {

    // 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

    compact := [][]int{
        {0, 0, 1, 1, 1, 3, 3, 3, 4}, // row indices
        {2, 4, 2, 3, 6, 1, 2, 5, 4}, // column indices
        {3, 8, 5, 7, 1, 2, 6, 4, 9}, // values
    }

    count := 9

    fmt.Println("Compact matrix:")
    for i := 0; i < 3; i++ {
        for j := 0; j < count; j++ {
            fmt.Printf("%d ", compact[i][j])
        }
        fmt.Println()
    }
    fmt.Println()

    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 4 hours ago by avibootz

Related questions

...