Learn-dsa..in 30 days!



























CC-20 :Restore matrix from row and column sums.

Description:

Given row and column sums arrays, restore matrix from it.

Test cases and expected outputs:

Input Expected outputs
SumRows : 3,8
SumCols : 4,7
The Restored Matrix :
3,0,
1,7,
SumRows : 4,8
SumCols : 5,7
The Restored Matrix :
4,0,
1,7,
SumRows : 6,8,11
SumCols : 9,7,9
The Restored Matrix :
6,0,0,
3,5,0,
0,2,9,

Pseudocode:

The java method should accept following input parameters: int array sumRows, int array sumCols.
Declare new int matrix named nMatrix with sumRows.length rows and sumCols.length columns.
Initialize variable min=0.
Iterate through nMatrix rows using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < nMatrix.length:
Iterate through nMatrix columns using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < nMatrix[0].length:
Check if (sumRows[rIdx] < sumCols[cIdx]) in that case set min to sumRows[rIdx] else set min to sumCols[cIdx].
Set nMatrix[rIdx][cIdx]=min.
Decrement sumRows[rIdx] by min.
Decrements sumCols[cIdx] by min.
When above for loops are completed, nMatrix contains elements restored based on row and column sums from from sumRows and sumCols. Return nMatrix.

Code:

public int[][] restoreMatrixFromSums(int[]sumRows, int[] sumCols) throws Exception{
	int[][] nMatrix=new int[sumRows.length][sumCols.length];
	int min=0;
	for (int rIdx=0; rIdx < sumRows.length; rIdx++) {
		for (int cIdx=0; cIdx < sumCols.length; cIdx++) {
			if (sumRows[rIdx] < sumCols[cIdx]) {
				min=sumRows[rIdx];
			}else {
				min=sumCols[cIdx];				
			}
			nMatrix[rIdx][cIdx]=min;
			sumRows[rIdx] -=min;
			sumCols[cIdx] -=min;
		}
	}
	return nMatrix;	
}

Click here to download and run code and test cases !