Search code examples
javamatrixgetter-setter

Sparse Matrices in Java


Sparse matrices are matrices whose elements are predominantly zero. The codes below use an ArrayList of LinkedLists to implement a sparse matrice. It defines a class Element to store the column number and value for an element. Each row is represented by a LinkedList of Elements with non-zero values only. Few, if any, rows are all zeros and so the ArrayList is used to store a LinkedList for every row in ascending row order.

class Element { 
  public int column; 
  public int value; }

public class SparseMatrix { 
  private int mRows; // Number of rows 
  private int mCols; // Number of columns 
  private ArrayList<LinkedList<Element>> mMatrix;

1) How do I make use of a getter with parameters (int r, int c) which presents a certain row and column number to retrieve the value within that row and column of the matrix?

2) How do I make use of a setter with parameters (int r, int c, int v), to set the value at row r and column c to v? (Note: If node is not already there, a new node must be created. If v is zero, remove the node.)

Please correct me if I am wrong, but to get the total number of rows and columns respectively for the matrix, I would do:

get(int r, int c) {
    int rowSize = mMatrix.length;
    int colSize = mMatrix[0].length;
    }

However, I am unsure of how to make use of this subsequently.


Solution

  • I'll just drop the code here with some elementary comments. You should be able to adjust it according to your needs. I wont use class Element since its holding an int. Significance of value column is irrelevant.

    private static int mRows; // Number of rows 
    private static int mCols; // Number of columns 
    private static final ArrayList<LinkedList<Integer>> mMatrix = new ArrayList<>();
    
    
    public static void main(String[] args) {
        mRows = 7; //example
        mCols = 4; //example
    
         //init your matrix
        for (int i = 0; i < mRows; i++) { //add new row 7 times
            mMatrix.add(new LinkedList<>());
            for (int j = 0; j < mCols; j++) {
                mMatrix.get(i).add(0); // add Integer with value 0 (4 times)
            }
        }
    
        //test
        setValue(5, 3, 159);
        System.out.println(getValue(5, 3));
    
    }
    
    public static void setValue(int r, int c, Integer v) {
        //before call be sure that r < mRows and c < mCols
        mMatrix.get(r).set(c, v); //replaces existing Integer
    }
    
    public static Integer getValue(int r, int c) {
        //before call be sure that r < mRows and c < mCols
        return mMatrix.get(r).get(c);
    }