Skip to content
the poor coder

Hackerrank - Reverse Game Solution

Poor Man
Published
Updated
Reading time
1 min read

Akash and Akhil are playing a game. They have  balls numbered from  to . Akhil asks Akash to reverse the position of the balls, i.e., to change the order from say, 0,1,2,3 to 3,2,1,0. He further asks Akash to reverse the position of the balls  times, each time starting from one position further to the right, till he reaches the last ball. So, Akash has to reverse the positions of the ball starting from  position, then from  position, then from  position and so on. At the end of the game, Akhil will ask Akash the final position of any ball numbered . Akash will win the game, if he can answer. Help Akash.

Input Format
The first line contains an integer , i.e., the number of the test cases.
The next  lines will contain two integers  and .

Output Format
Print the final index of ball  in the array.

Constraints


Sample Input

Text
2
3 1
5 2

Sample Output

Text
2
4

Explanation
For first test case, The rotation will be like this:
0 1 2 -> 2 1 0 -> 2 0 1 -> 2 0 1
So, Index of 1 will be 2.

Solution in Python#

Python
from collections import deque
def reverse_index(n,k):
    for i in range(n):
        x = a.popleft() if i%2 else a.pop()
        if x==k: return i

for _ in range(int(input())):
    n,k = map(int,input().split())
    a = deque(range(n))
    print(reverse_index(n,k))

Keep going

2020

Hackerrank - Bus Station Solution

There are groups of friends, and each group is numbered from 1 to . The th group contains people. They live near a bus stop, and only a single bus operates on this route. An empty bus arrives at the bus stop and all the…

2020

Hackerrank - K Candy Store Solution

Jim enters a candy shop which has N different types of candies, each candy is of the same price. Jim has enough money to buy K candies. In how many different ways can he purchase K candies if there are infinite candies…

2020

Hackerrank - Diwali Lights Solution

On the eve of Diwali, Hari is decorating his house with a serial light bulb set. The serial light bulb set has N bulbs placed sequentially on a string which is programmed to change patterns every second. If at least one…

ESC