Search code examples
dartmemoization

How to implement memoization in dart?


Hi Everyone, I am new to dart, I tried to implement memoization but it is not working, please tell me how to implement memoization. Thanks in advance.

int memoizedFibonacci(n,{memo:null}) {
  if(memo == null){
    memo = Map();
  }
  if(memo.containsKey(n)){
    return memo[n];
  }else{
    memo[n] = memoizedFibonacci(n-1, memo:memo) + memoizedFibonacci(n-2, memo: memo);
  }
  return memo[n];
}
main() {
  print(memoizedFibonacci(10));
}

Error: Unhandled exception: Stack Overflow #0 int.hashCode (dart:core-patch/integers.dart:541:3) #1 _OperatorEqualsAndHashCode._hashCode (dart:collection-patch/compact_hash.dart:149:25) #2 _LinkedHashMapMixin._getValueOrData (dart:collection-patch/compact_hash.dart:355:26) #3 _LinkedHashMapMixin.containsKey (dart:collection-patch/compact_hash.dart:375:54)


Solution

  • Memoization is a concept. You can store it wherever you want, in my example below, I store it in my Fibonacci List, and take it from there.

      int val = 7;
      List<int> fib = [0, 1];
      DateTime start = DateTime.now();
      for (int i = fib.length; i <= val; i++) {
        fib.add(fib[i - 1] + fib[i - 2]);
      }
      // [0, 1, 1, 2, 3, 5, 8, 13]