You are given an integer n
representing the number of people in a circle and an integer time
representing the total time (in minutes) that the pillow has been passed around.
The pillow passing starts with the first person and moves to the next person every minute. The direction of passing needs to alternate each time, one minute to the right, one minute to the left, and so on.
Write a function pass_the_pillow(n: int, time: int) -> int
that returns the position of the person who receives the pillow after the given amount of time.
time
is non-negative and n
is greater than 0.def pass_the_pillow(n: int, time: int) -> int:
# Initial position of the pillow, start from person 1
position = 1
# determine full cycles and remaining moves
full_cycles, remainder = divmod(time, n-1)
# If full_cycles is even, final direction will be same as initial, right
if full_cycles % 2 == 0:
# Moving to the right by remainder
position = (position - 1 + remainder) % n + 1
else:
# Moving to the left by remainder
position = (position - 1 - remainder) % n + 1
return position
# Test case
print(pass_the_pillow(4, 5)) # Output should be 1
n-1
passes make a full cycle) the pillow has completed.remainder
.remainder
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?