Find the position of box which occupies the given ball | Function to print the position of each boxes where a ball has to be placed ; Find the cumulative sum of array A ; Find the position of box for each ball ; Row number ; Column ( position of box in particular row ) ; Row + 1 denotes row if indexing of array start from 1 ; Driver code
function printPosition ( A , B , sizeOfA , sizeOfB ) { for ( i = 1 ; i < sizeOfA ; i ++ ) { A [ i ] += A [ i - 1 ] ; } for ( i = 0 ; i < sizeOfB ; i ++ ) { var row = lower_bound ( A , 0 , A . length , B [ i ] ) ; var boxNumber = ( row >= 1 ) ? B [ i ] - A [ row - 1 ] : B [ i ] ; document . write ( row + 1 + " " + boxNumber + " " ) ; } } function lower_bound ( a , low , high , element ) { while ( low < high ) { var middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) { low = middle + 1 ; } else { high = middle ; } } return low ; } var A = [ 2 , 2 , 2 , 2 ] ; var B = [ 1 , 2 , 3 , 4 ] ; var sizeOfA = A . length ; var sizeOfB = B . length ; printPosition ( A , B , sizeOfA , sizeOfB ) ;