// C# program to find sparse matrix
// resentation using CSR
using System;
using System.Collections.Generic;
class GFG {
// Utility Function to print a Matrix
static void printMatrix(int[, ] M)
{
int m = M.GetLength(0);
int n = M.GetLength(1);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
Console.Write(M[i, j] + " ");
Console.WriteLine();
}
}
// Utility Function to print A, IA, JA vectors
// with some decoration.
static void printVector(List<int> V, string msg)
{
Console.Write(msg + "[ ");
foreach(var a in V) { Console.Write(a + " "); }
Console.WriteLine("]");
}
// Generate the three vectors A, IA, JA
static void sparesify(int[, ] M)
{
int m = M.GetLength(0);
int n = M.GetLength(1), i, j;
List<int> A = new List<int>();
List<int> IA
= new List<int>(); // IA matrix has N+1 rows
List<int> JA = new List<int>();
int NNZ = 0;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (M[i, j] != 0) {
A.Add(M[i, j]);
JA.Add(j);
// Count Number of Non Zero
// Elements in row i
NNZ++;
}
}
IA.Add(NNZ);
}
printMatrix(M);
printVector(A, "A = ");
printVector(IA, "IA = ");
printVector(JA, "JA = ");
}
// Driver code
public static void Main()
{
int[, ] M = {
{ 0, 0, 0, 0, 1 },
{ 5, 8, 0, 0, 0 },
{ 0, 0, 3, 0, 0 },
{ 0, 6, 0, 0, 1 },
};
// Function call
sparesify(M);
}
}
// This code is contributed by Aarti_Rathi