Lesson 5.17 · Write it
Take turns on the console
A functionPython or Java11 tests, 7 of them hidden
On a phone? Put the lines in order instead
A games club has one console, and the players share it fairly by taking turns. Write a function that works out the order of the turns.
- The players are numbered 0, 1, 2 and so on.
turnsholds how many turns each player wants: player 0 wantsturns[0]turns, player 1 wantsturns[1], and so on. There are 1 to 10 players, and each wants a whole number of turns from 1 to 5. - At the start, the players stand in a queue in number order, so player 0 is at the front.
- Again and again, the player at the front leaves the queue and plays one turn. If that player still wants more turns, they join the back of the queue. If not, they are done.
- When the queue is empty, every turn has been played.
- Return a list of the player numbers in the order the turns were played, one number for each turn.
For example, if turns holds 2, 1 and 3, the turns go to players 0, 1, 2, 0, 2, 2.
Only the value your function returns is checked.
def round_robin_turns(turns: list[int]) -> list[int]
Examples
Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.
- round_robin_turns([2, 1, 3]) should return [0, 1, 2, 0, 2, 2]: the example in the question (rules 3 and 5)
- round_robin_turns([1, 1, 1]) should return [0, 1, 2]: one turn each, so each player is done after one go (rule 3)
- round_robin_turns([3, 1]) should return [0, 1, 0, 0]: player 0 is left alone in the queue and plays on (rules 3 and 4)
- round_robin_turns([1]) should return [0]: one player who wants one turn (rule 4)
public static ArrayList<Integer> roundRobinTurns(int[] turns)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.
- roundRobinTurns(new int[]{2, 1, 3}) should return [0, 1, 2, 0, 2, 2]: the example in the question (rules 3 and 5)
- roundRobinTurns(new int[]{1, 1, 1}) should return [0, 1, 2]: one turn each, so each player is done after one go (rule 3)
- roundRobinTurns(new int[]{3, 1}) should return [0, 1, 0, 0]: player 0 is left alone in the queue and plays on (rules 3 and 4)
- roundRobinTurns(new int[]{1}) should return [0]: one player who wants one turn (rule 4)