Created
          January 11, 2022 01:30 
        
      - 
      
- 
        Save kranfix/d1a136c05955a4d3aa5e589a63f659a3 to your computer and use it in GitHub Desktop. 
    Playing with fibonacci
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | void main() { | |
| print(fibo(3)); | |
| print(fibo(5)); | |
| print(fibo(13)); | |
| print(fibo(8)); | |
| } | |
| // TODO: refactorizar usando cache | |
| int fibox(int n) { | |
| assert(n >= 1, 'No es posible calcular fib($n)'); | |
| int a = 1; | |
| int b = 1; | |
| for(int i = 1; i < n; i++) { | |
| int f = b + a; | |
| a = b; | |
| b = f; | |
| print('calc: $i - $f'); | |
| } | |
| return b; | |
| } | |
| List<int> cache = [0, 1, 1]; | |
| int fibo(int n) { | |
| assert(n >= 1, 'No es posible calcular fib($n)'); | |
| if(n < cache.length) { | |
| print('$n - $cache'); | |
| return cache[n]; | |
| } | |
| for(int i = cache.length; i <= n; i++) { | |
| int f = cache[i-1] + cache[i-2]; | |
| print('calc: $i - $f'); | |
| cache.add(f); | |
| } | |
| print('$n - $cache'); | |
| return cache.last; | |
| } | |
| int fib(int n) { | |
| final cache = <int>[0, 1, 1]; | |
| int a = _fib(n, cache); | |
| print('cache: $cache'); | |
| return a; | |
| } | |
| int _fib(int n, List<int> cache) { | |
| assert(n >= 1, 'No es posible calcular fib($n)'); | |
| if(cache.length > n){ | |
| print('Calculando fib($n) - $cache'); | |
| return cache[n]; | |
| } | |
| if(cache.length == n) { | |
| int f = cache[n - 1] + cache[n - 2]; | |
| cache.add(f); | |
| print('Calculando fib($n) - $cache'); | |
| return f; | |
| } | |
| print('Calculando fib($n) - $cache'); | |
| int f = _fib(n-1, cache) + cache[n-2]; | |
| cache.add(f); | |
| return f; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment