Next Mayor
InterviewTime limit1sMemory limit128 MB
Simulate the pebble-passing game and output the index of the candidate who ends up holding every pebble.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation
- Solved
- No attempts yet
Problem
One of the strangest traditions of the town of Gameston is that even the next mayor is chosen by the result of a game. When a mayor's term is about to expire, at least three candidates -- including the current mayor -- play a game with pebbles, and the winner becomes the next mayor.
The rules of the pebble game are as follows. Below, is the number of participating candidates.
- Equipment
- A round table, a bowl, and plenty of pebbles.
- Setup
- Some pebbles are placed in the bowl. All candidates, numbered to , sit around the round table in counterclockwise order. At the start, the bowl is given to the current mayor, who is candidate .
- A turn
- When a candidate receives the bowl:
- If the bowl holds at least one pebble, the candidate takes exactly one pebble out and keeps it together with any pebbles already in hand.
- If the bowl is empty, the candidate puts all pebbles currently in hand (if any) into the bowl.
- In either case, the candidate then passes the bowl to the next candidate on the right (candidate ). This repeats until a winner is decided.
- When a candidate receives the bowl:
- End of the game
- The moment a candidate takes the last pebble from the bowl and no other candidate is holding any pebbles, the game ends, and that candidate -- now holding every pebble -- is the winner.
It has been proven that this game always ends after a finite number of turns, although that number can be very large.
Input
The input consists of several datasets. Each dataset is a single line with two integers and separated by one space, where is the number of candidates (including the current mayor) and is the total number of pebbles initially placed in the bowl. You may assume and .
For every dataset in the input, the game ends within 1,000,000 turns.
The input ends with a line containing two zeros separated by a single space; this line must not be processed.
Output
For each dataset, output a single line containing the number of the winning candidate, in the same order as the input. No other characters may appear in the output.