Generate a matrix with each row and column of given sum | Java program for the above approach ; Function to generate a matrix with sum of each row equal to sum of r [ ] and sum of each column equal to sum of c [ ] ; Initialize a matrix ; Traverse each cell ( i , j ) of the matrix ; Assign the minimum of the row or column value ; Subtract the minimum from both row and column sum ; Print the matrix obtained ; Driver Code
import java . io . * ; class GFG { static int [ ] [ ] restoreGem ( int [ ] r , int [ ] c ) { int [ ] [ ] dp = new int [ r . length ] [ c . length ] ; for ( int i = 0 ; i < r . length ; i ++ ) { for ( int j = 0 ; j < c . length ; j ++ ) { int m = Math . min ( r [ i ] , c [ j ] ) ; dp [ i ] [ j ] = m ; r [ i ] -= m ; c [ j ] -= m ; } } return dp ; } static void printMatrix ( int [ ] [ ] ans , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { System . out . print ( ans [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] rowSum = { 5 , 7 , 10 } ; int [ ] colSum = { 8 , 6 , 8 } ; int [ ] [ ] ans = restoreGem ( rowSum , colSum ) ; printMatrix ( ans , rowSum . length , colSum . length ) ; } }