Minimum operations of given type to make all elements of a matrix equal | Function to return the minimum number of operations required ; Create another array to store the elements of matrix ; If not possible ; Sort the array to get median ; To count the minimum operations ; If there are even elements , then there are two medians . We consider the best of two as answer . ; Return minimum operations required ; Driver code
function minOperations ( n , m , k , matrix ) { let arr = new Array ( n * m ) ; arr . fill ( 0 ) ; let mod = matrix [ 0 ] [ 0 ] % k ; for ( let i = 0 ; i < n ; ++ i ) { for ( let j = 0 ; j < m ; ++ j ) { arr [ i * m + j ] = matrix [ i ] [ j ] ; if ( matrix [ i ] [ j ] % k != mod ) { return - 1 ; } } } arr . sort ( function ( a , b ) { return a - b } ) ; let median = arr [ parseInt ( ( n * m ) / 2 , 10 ) ] ; let minOperations = 0 ; for ( let i = 0 ; i < n * m ; ++ i ) minOperations += parseInt ( Math . abs ( arr [ i ] - median ) / k , 10 ) ; if ( ( n * m ) % 2 == 0 ) { let median2 = arr [ parseInt ( ( n * m ) / 2 , 10 ) ] ; let minOperations2 = 0 ; for ( let i = 0 ; i < n * m ; ++ i ) minOperations2 += parseInt ( Math . abs ( arr [ i ] - median2 ) / k , 10 ) ; minOperations = Math . min ( minOperations , minOperations2 ) ; } return minOperations ; } let matrix = [ [ 2 , 4 , 6 ] , [ 8 , 10 , 12 ] , [ 14 , 16 , 18 ] , [ 20 , 22 , 24 ] ] ; let n = 4 ; let m = 3 ; let k = 2 ; document . write ( minOperations ( n , m , k , matrix ) ) ;