Find the position of box which occupies the given ball | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 , A + sizeOfA , B [ i ] ) - A ; int boxNumber = ( row >= 1 ) ? B [ i ] - A [ row - 1 ] : B [ i ] ; cout << row + 1 << " , ▁ " << boxNumber << " STRNEWLINE " ; } } int main ( ) { int A [ ] = { 2 , 2 , 2 , 2 } ; int B [ ] = { 1 , 2 , 3 , 4 } ; int sizeOfA = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int sizeOfB = sizeof ( B ) / sizeof ( B [ 0 ] ) ; printPosition ( A , B , sizeOfA , sizeOfB ) ; return 0 ; }