Queries to check if it is possible to join boxes in a circle | Javascript implementation of above approach ; Print the answer to each query ; setting the flag for exception ; replacing the greater element in i and j ; checking if that box is not used in previous query . ; checking if connecting to the same box ; case 1 : x < i and y lies between i and j ; case 2 : x lies between i and j and y > j ; if flag is not reset inbetween . ; Driver code
var MAX = 50 function solveQuery ( n , q , qi , qj ) { var arr = Array ( MAX ) ; for ( var i = 0 ; i <= n ; i ++ ) arr [ i ] = 0 ; for ( var k = 0 ; k < q ; k ++ ) { var flag = 0 ; if ( qj [ k ] < qi [ k ] ) { var temp = qi [ k ] ; qi [ k ] = qj [ k ] ; qj [ k ] = temp ; } if ( arr [ qi [ k ] ] != 0 arr [ qj [ k ] ] != 0 ) flag = 1 ; else if ( qi [ k ] == qj [ k ] ) flag = 1 ; else { for ( var i = 1 ; i < qi [ k ] ; i ++ ) { if ( arr [ i ] != 0 && arr [ i ] < qj [ k ] && qi [ k ] < arr [ i ] ) { flag = 1 ; break ; } } if ( flag == 0 ) { for ( var i = qi [ k ] + 1 ; i < qj [ k ] ; i ++ ) { if ( arr [ i ] != 0 && arr [ i ] > qj [ k ] ) { flag = 1 ; break ; } } } } if ( flag == 0 ) { document . write ( " " ) ; arr [ qi [ k ] ] = qj [ k ] ; arr [ qj [ k ] ] = qi [ k ] ; } else document . write ( " " ) ; } } var n = 10 ; var q = 7 ; var qi = [ 1 , 2 , 2 , 2 , 9 , 10 , 8 ] ; var qj = [ 5 , 7 , 3 , 4 , 9 , 9 , 6 ] ; solveQuery ( n , q , qi , qj ) ;