Batmanacci: a Fibonacci sequence, but with letters

975 Views Asked by At

I stumbled upon the Batmanacci problem (via kattis.com), where we have a Fibonacci sequence that starts with $a_1 = \text{'N'}$ and $a_2 = \text{'A'}$, and uses concatenation instead of addition. We need to know what $k$-th letter of the $n$-th term in the sequence is.

Because string concatenation takes too long, the following is the correct solution by Michael Pfeifer (via github.com), that I do not understand:

The algorithm for the solution of this problem is the following:

Instead of letters we say that we have $a_1 = 0$ and $a_2 = 1$ and then $a_3 = a_1 + a_2$.

To get the letter out of the sequence of these sums we then do (Python code):

while n > 2:
   if k > fib[n-2]:
       k -= fib[n-2]
       n -= 1
   else:
       n -= 2

Where fib is the list of the sums, n is the number of sums (length of the list), and k is the letter position of the letter we want to get (if we look all the list as one long word).

Then if at the end of the loop n is equal to 2, the letter is "A" and if n is equal to 1, then the letter is "N".

However I do not understand how this solution works.