There are many ways to represent sparse matrix, one of them is called COO, coordinate list which is list of tuples storing row index, column index and its value; See wiki page for COO: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_.28COO.29
Now we need to transpose a sparse matrix with COO list to another COO list. Below is the code with comments containing the detailed explanation of the algorithm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//given a sparce matrix Coordinate list (COO) representation, transpose the matrix and output new COO representation | |
//first, for each tuple in the list; (r, c, v), it will map to (c, r, v) in the final output | |
//second, when go through the COO list from index at 0 to the last item COO.length-1, we need to calculate | |
//the correponding index in the new COO | |
//the observation is that for the COO tuples in the first row will transpose to first column in new COO, | |
//and its index equals to the total number of COO tuples in the previous rows | |
//so we need an array to record the total number of COO tuples in previous rows for any given row | |
//we also need to update the numbers in the array when we generate new tuples in each row | |
//you need to try out samples and draw pictures to understand the last two sentences | |
class Solution { | |
static class Tuple { | |
int r, c, v; | |
public Tuple(int r, int c, int v){ | |
this.r = r; this.c = c; this.v = v; | |
} | |
} | |
//input are tuples and number of rows and cols | |
//output are the tuples array after the transpose | |
public static Tuple[] transpose(Tuple[] input, int rows, int cols){ | |
//first create the assessary array to store the numbers of tuples for any given row for the new matrix | |
//this is done by counting the tuples in each column of the original matrix | |
int[] values = new int[cols]; | |
for(Tuple t : input){ | |
values[t.c]++: | |
} | |
//then we build the array store the total numbers of tuples in previous rows for any given row for the new matrix | |
int[] rows = new int[cols]; | |
rows[0] = 0; | |
for(int r = 1; r<cols; r++){ | |
rows[r] = rows[r-1] + values[r-1]; | |
} | |
//now we can do the tranposition | |
Tuple[] ret = new Tuple[input.length]; | |
for(Tuple t : input){ | |
//so far there are rows[t.c] tuples before the current tuple we are creating here | |
ret[rows[t.c]] = new Tuple(t.c, t.r, t.v); | |
//remember we have to update the count | |
rows[t.c]++; | |
} | |
return ret; | |
} | |
} |