Construct a matrix such that union of ith row and ith column contains every element from 1 to 2 N | Javascript implementation of the above approach ; Function to find the square matrix ; For Matrix of order 1 , it will contain only 1 ; For Matrix of odd order , it is not possible ; For Matrix of even order ; All diagonal elements of the matrix can be N itself . ; Assign values at desired place in the matrix ; Loop to add N in the lower half of the matrix such that it contains elements from 1 to 2 * N - 1 ; Loop to print the matrix ; Driver Code
let matrix = new Array ( ) ; for ( let i = 0 ; i < 100 ; i ++ ) { let temp = new Array ( ) ; for ( let j = 0 ; j < 100 ; j ++ ) { temp . push ( [ ] ) } matrix . push ( temp ) } function printRequiredMatrix ( n ) { if ( n == 1 ) { document . write ( " " + " " ) ; } else if ( n % 2 != 0 ) { document . write ( " " + " " ) ; } else { for ( let i = 0 ; i < n ; i ++ ) { matrix [ i ] [ i ] = n ; } let u = n - 1 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { matrix [ i ] [ u ] = i + 1 ; for ( let j = 1 ; j < n / 2 ; j ++ ) { let a = ( i + j ) % ( n - 1 ) ; let b = ( i - j + n - 1 ) % ( n - 1 ) ; if ( a < b ) { let temp = a ; a = b ; b = temp } matrix [ b ] [ a ] = i + 1 ; } } for ( let i = 0 ; i < n ; i ++ ) for ( let j = 0 ; j < i ; j ++ ) matrix [ i ] [ j ] = matrix [ j ] [ i ] + n ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) document . write ( matrix [ i ] [ j ] + " " ) ; document . write ( " " ) ; } } document . write ( " " ) ; } let n = 1 ; printRequiredMatrix ( n ) ; n = 3 ; printRequiredMatrix ( n ) ; n = 6 ; printRequiredMatrix ( n ) ;