You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it.
While you wait for your flight, you decide to check in with the Elves back at the North Pole. They’re playing a memory game and are ever so excited to explain the rules!
In this game, the players take turns saying numbers. They begin by taking turns reading from a list of starting numbers. Then, each turn consists of considering the most recently spoken number:
0
.So, after the starting numbers, each turn results in that player speaking aloud either 0
(if the last number is new) or an age (if the last number is a repeat).
For example, suppose the starting numbers are 0,3,6
:
0
.3
.6
.6
. Since that was the first time the number had been spoken, the 4
th number spoken is 0
.0
. Since it had been spoken before, the next number to speak is the difference between the turn number when it was last spoken (the previous turn, 4
) and the turn number of the time it was most recently spoken before then (turn 1
). Thus, the 5
th number spoken is 4 - 1
, 3
.3
had also been spoken before, most recently on turns 5
and 2
. So, the 6
th number spoken is 5 - 2
, 3
.3
was just spoken twice in a row, and the last two turns are 1
turn apart, the 7
th number spoken is 1
.1
is new, the 8
th number spoken is 0
.0
was last spoken on turns 8
and 4
, so the 9
th number spoken is the difference between them, 4
.4
is new, so the 10
th number spoken is 0
.(The game ends when the Elves get sick of playing or dinner is ready, whichever comes first.)
Their question for you is: what will be the 2020
th number spoken? In the example above, the 2020
th number spoken will be 436
.
Here are a few more examples:
1,3,2
, the 2020
th number spoken is 1
.2,1,3
, the 2020
th number spoken is 10
.1,2,3
, the 2020
th number spoken is 27
.2,3,1
, the 2020
th number spoken is 78
.3,2,1
, the 2020
th number spoken is 438
.3,1,2
, the 2020
th number spoken is 1836
.Given your starting numbers, what will be the 2020
th number spoken? Determine this in the following way:
recitation
that takes a list of starting numbers (String
). The function must return the 2020
th number (Number
) spoken.> recitation("0,3,6")
436
> recitation("1,3,2")
1
> recitation("2,1,3")
10
> recitation("1,2,3")
27
> recitation("2,3,1")
78
> recitation("3,2,1")
438
> recitation("3,1,2")
1836