Suppose we have two arrays A and B. The size of A is the number of rows and A[i] is the number of boxes in the ith row. And B is the array of balls where B[i] denotes a number on the ball. Given that ball i (value B[i]) will be placed in a box whose position from starting is B[i]. We have to find the row and column of the boxes corresponding to each B[i].
So, if the input is like A = [3, 4, 5, 6], B = [1, 3, 5, 2], then the output will be [(1, 1), (1, 3), (2, 2), (1, 2)] as B[0] = 1, then the box position will be 1st row, 1st column B[1] = 3, then the box position will be 1st row, 3rd column, B[2] = 5, then the box position will be 2nd row, 2nd column, B[3] = 2, then the box position will be 1st row, 2nd column
To solve this, we will follow these steps −
len_a := size of A
len_b := size of B
for i in range 1 to len_a, do
A[i] := A[i] + A[i - 1]
for i in range 0 to len_b, do
row := an index where we can insert B[i] to maintain A sorted
if row >= 1, then
box_num := B[i] - A[row - 1]
otherwise,
box_num := B[i]
display a pair (row + 1, box_num)
Example
Let us see the following implementation to get better understanding −
import bisect def get_position(A, B): len_a = len(A) len_b = len(B) for i in range(1, len_a): A[i] += A[i - 1] for i in range(len_b): row = bisect.bisect_left(A, B[i]) if row >= 1: box_num = B[i] - A[row - 1] else: box_num = B[i] print ((row + 1, box_num)) A = [3, 4, 5, 6] B = [1, 3, 5, 2] get_position(A, B)
Input
[3, 4, 5, 6], [1, 3, 5, 2]
Output
(1, 1) (1, 3) (2, 2) (1, 2)