To implement a sparse matrix using a map in Go, you can follow these steps:
type SparseMatrix struct {
rows, cols int
data map[int]map[int]int
}
func NewSparseMatrix(rows, cols int) SparseMatrix {
return SparseMatrix{
rows: rows,
cols: cols,
data: make(map[int]map[int]int),
}
}
func (sm *SparseMatrix) Set(row, col, value int) {
if sm.data[row] == nil {
sm.data[row] = make(map[int]int)
}
sm.data[row][col] = value
}
func (sm *SparseMatrix) Get(row, col int) int {
if sm.data[row] == nil {
return 0 // Return 0 for positions with no value
}
return sm.data[row][col]
}
func (sm *SparseMatrix) Print() {
for row := 0; row < sm.rows; row++ {
for col := 0; col < sm.cols; col++ {
fmt.Printf("%d ", sm.Get(row, col))
}
fmt.Println()
}
}
Here's an example of how to use this sparse matrix implementation:
func main() {
matrix := NewSparseMatrix(3, 3)
matrix.Set(0, 0, 1)
matrix.Set(1, 1, 2)
matrix.Set(2, 2, 3)
matrix.Print()
fmt.Println(matrix.Get(0, 0)) // Output: 1
fmt.Println(matrix.Get(1, 1)) // Output: 2
fmt.Println(matrix.Get(2, 2)) // Output: 3
}
This implementation of a sparse matrix using a map in Go allows you to efficiently represent matrices with a large number of zero values.