Suppose, there are n number of balls. The balls are ordered in a fashion 1,2,3,4,...,n. Now the balls are reversed in order, or ordered in a way n, n-1, n-2, ......, 2, 1. The balls are again reversed in order, this time they are reversed from position 1 to n, or now the order becomes n, 1, 2,....., n-1. This reversing process is repeated n times and each time the starting position is moved 1 place to the right. We now have to find out the position of a ball initially in position 'index' after the reversals.
So, if the input is like balls = 5, index = 2, then the output will be 4 The balls initially are: 1, 2, 3, 4, 5
5,4,3,2,1 5,1,2,3,4 5,1,4,3,2 5,1,4,2,3
The ball in position 2 is currently at position 4.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(balls, index): if index < balls // 2: return 2 * index + 1 else: return 2 * (balls - index - 1) print(solve(5, 2))