How to implement a sparse matrix using a map in Go?

To implement a sparse matrix using a map in Go, you can follow these steps:

  1. Define a struct to represent a sparse matrix:
type SparseMatrix struct { rows, cols int data map[int]map[int]int }
  1. Create a function to initialize a new sparse matrix with a given number of rows and columns:
func NewSparseMatrix(rows, cols int) SparseMatrix { return SparseMatrix{ rows: rows, cols: cols, data: make(map[int]map[int]int), } }
  1. Implement a method to set a value at a specific position in the matrix:
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 }
  1. Implement a method to get a value from a specific position in the matrix:
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] }
  1. Optionally, implement a method to print the matrix in a readable format:
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.