CLEAN CODE: HACKER RANK FIBONACCI LITE

By: Saurav

2017-12-27 02:33:00 UTC

For this question, you will write a program that generates values from the Fibonacci sequence. The Fibonnaci sequence is recursively defined by:

Fn = Fn - 1 + Fn - 2

Using the following seed values:

F0 = 0, F1 = 1

Given a number n, print the nth value of the Fibonacci sequence.

Examples
Input:

12
Output:

144
Input:

30
Output:

832040

HackerRank

The question itself gives the tests we can use.

Without wasting much effort on the bad algorithm, I will jump ahead to using memoization with Hash.

def fibonacci_helper(n)
   n = n.to_i
  
  return 0 if n < 1 
  
  return 1 if n ==1 or n == 2 
  dictionary = Hash.new 
  dictionary[1] = 1
  dictionary[2] = 1 
  
  return fibonacci(n, dictionary)
end 

def fibonacci(n,dictionary)
    
  if dictionary.key?(n)
    return dictionary[n]
    
  end
  
  return fibonacci(n-1, dictionary) + fibonacci(n-2, dictionary)
end 

Let's Clean it a little bit.

def fibonacci_helper(n, dictionary = Hash.new)
   n = n.to_i
   
  return 0 if n < 1 
  dictionary[1],dictionary[2]  = 1,1 
  
  n < 3 ? 1 : fibonacci(n, dictionary)
  
  return fibonacci(n, dictionary)
end 

def fibonacci(n,dictionary)
  return dictionary[n] if dictionary.key?(n)
  return fibonacci(n-1, dictionary) + fibonacci(n-2, dictionary)
end 

fibonacci_helper(3)


Let me know what you think!
Twitter: sprakash24oct
Linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)