DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#12 - Fibonacci digit sequence CodeWars Kata (6 kyu)

Instructions

Task
You are given three non negative integers a, b and n, and making an infinite sequence just like fibonacci sequence, use the following rules:

step 1: use ab as the initial sequence.
step 2: calculate the sum of the last two digits of the sequence, and append it to the end of sequence.
repeat step 2 until you have enough digits
Your task is to complete the function which returns the nth digit (0-based) of the sequence.

Notes:
0 <= a, b <= 9, 0 <= n <= 10^10
16 fixed testcases
100 random testcases, testing for correctness of solution
100 random testcases, testing for performance of code
All inputs are valid.
Pay attention to code performance.

Examples

For a = 7, b = 8 and n = 9 the output should be 5, because the sequence is:
78 -> 7815 -> 78156 -> 7815611 -> 78156112 -> 781561123 -> 7815611235 -> ...
and the 9th digit of the sequence is 5.


For a = 0, b = 0 and n = 100000000 the output should be 0, because all the digits in this sequence are 0.


My solution:

function find(a,b,n){
  let r = a.toString() + b.toString()
  n = +n.toString().slice(-4);

  while (r.length <= n){
   let x = r.split('')
   r += (+x[x.length-1] + +x[x.length-2]).toString()
  }

  return +r.charAt(n)
}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I started concatinating the 2 first numbers as a string, then I changed the n value, because if it was too high, the code performance would be awful and it tooka lot to returning the result, so I just used the last 4 numbers of the n variable because after some cycles, the result is the same.

let r = a.toString() + b.toString()
n = +n.toString().slice(-4);


After that I used a while loop that would keep iterating until the string "r" length is equal to "n", inside the loop I made a variable "x" that splitted the "r" string into an array and after that the "r" string will concatenate and be equal to the sum of the last 2 elements of the "x" array, for making this strings a number I just added the + operator before the values, and after summing them I just made them string again so for the next loop cycle it would be a string again.

r += (+x[x.length-1] + +x[x.length-2]).toString()


At the end I just returned the character at the "n" position of the "r" string, and converted it to a number because I used the + operator before returning the value.

return +r.charAt(n)


Comment how would you solve this kata and why? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (2)

Collapse
 
namhle profile image
Nam Hoang Le

It could work the string length is growing too much. Just keep the last two characters instead 👌🏻

Collapse
 
cesar__dlr profile image
Cesar Del rio

Yeah, maybe I could just keep the last two characters and keep concatinating them to the main string, so I don't have to continue splitting the main string in every loop.

Good contribution 🙌