Minimum cost to sort a matrix of numbers from 0 to n ^ 2 | Javascript implementation to find the total energy required to rearrange the numbers ; function to find the total energy required to rearrange the numbers ; nested loops to access the elements of the given matrix ; store quotient ; final destination location ( i_des , j_des ) of the element mat [ i ] [ j ] is being calculated ; energy required for the movement of the element mat [ i ] [ j ] is calculated and then accumulated in the ' tot _ energy ' ; required total energy ; driver program
let SIZE = 100 ; function calculateEnergy ( mat , n ) { let i_des , j_des , q ; let tot_energy = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) { q = Math . floor ( mat [ i ] [ j ] / n ) ; i_des = q ; j_des = mat [ i ] [ j ] - ( n * q ) ; tot_energy += Math . abs ( i_des - i ) + Math . abs ( j_des - j ) ; } } return tot_energy ; } let mat = [ [ 4 , 7 , 0 , 3 ] , [ 8 , 5 , 6 , 1 ] , [ 9 , 11 , 10 , 2 ] , [ 15 , 13 , 14 , 12 ] ] ; let n = 4 ; document . write ( " " + calculateEnergy ( mat , n ) + " " ) ;