Find if a binary matrix exists with given row and column sums | Function to check if matrix exists ; Store sum of rowsums , max of row sum number of non zero row sums ; Store sum of column sums , max of column sum number of non zero column sums ; Check condition 1 , 2 , 3 ; Driver Code
function matrix_exist ( row , column , r , c ) { var row_sum = 0 ; var column_sum = 0 ; var row_max = - 1 ; var column_max = - 1 ; var row_non_zero = 0 ; var column_non_zero = 0 ; for ( var i = 0 ; i < r ; i ++ ) { row_sum += row [ i ] ; row_max = Math . max ( row_max , row [ i ] ) ; if ( row [ i ] ) row_non_zero ++ ; } for ( var i = 0 ; i < c ; i ++ ) { column_sum += column [ i ] ; column_max = Math . max ( column_max , column [ i ] ) ; if ( column [ i ] ) column_non_zero ++ ; } if ( ( row_sum != column_sum ) || ( row_max > column_non_zero ) || ( column_max > row_non_zero ) ) return false ; return true ; } var row = [ 2 , 2 , 2 , 2 , 2 ] ; var column = [ 5 , 5 , 0 , 0 ] ; var r = row . length ; var c = column . length ; if ( matrix_exist ( row , column , r , c ) ) document . write ( " " ) ; else document . write ( " " ) ;