Find the position of box which occupies the given ball | Java implementation of the approach ; 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
class GFG { static void printPosition ( int A [ ] , int B [ ] , int sizeOfA , int sizeOfB ) { for ( int i = 1 ; i < sizeOfA ; i ++ ) { A [ i ] += A [ i - 1 ] ; } for ( int i = 0 ; i < sizeOfB ; i ++ ) { int row = lower_bound ( A , 0 , A . length , B [ i ] ) ; int boxNumber = ( row >= 1 ) ? B [ i ] - A [ row - 1 ] : B [ i ] ; System . out . print ( row + 1 + " , ▁ " + boxNumber + "NEW_LINE"); } } private static int lower_bound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) { low = middle + 1 ; } else { high = middle ; } } return low ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 2 , 2 , 2 } ; int B [ ] = { 1 , 2 , 3 , 4 } ; int sizeOfA = A . length ; int sizeOfB = B . length ; printPosition ( A , B , sizeOfA , sizeOfB ) ; } }