Skip to content

Instantly share code, notes, and snippets.

@danveloper
Last active December 16, 2015 08:19
Show Gist options
  • Save danveloper/5405437 to your computer and use it in GitHub Desktop.
Save danveloper/5405437 to your computer and use it in GitHub Desktop.
Memoized Fibonacci calculation using lambdas in Java 8
public class MemoizedLambdaFib {
interface MemoizedFunction<T, R> {
enum Cache {
_;
Map<Object, Object> vals = new HashMap<>();
}
R calc(T t);
public default R apply(T t) {
if (!Cache._.vals.containsKey(t)) {
Cache._.vals.put(t, calc(t));
}
return (R)Cache._.vals.get(t);
}
}
static final MemoizedFunction<Integer, Integer> fib = (Integer n) -> {
if (n == 0 || n == 1) return n;
return fib.apply(n - 1)+fib.apply(n-2);
};
public static void main(String[] args) {
System.out.println(fib.apply(20));
}
}
@edalorzo
Copy link

edalorzo commented May 9, 2013

I believe that with the addition of the method computeIfAbsent in the interface Map, this can be greatly simplified to:

static Map<Integer,Long> memo = new HashMap<>();

static {
  memo.put(0,0L);
  memo.put(1,1L);
}

public static long fibonacci(int x) {
  return memo.computeIfAbsent(x, n -> fibonacci(n-1), fibonacci(n-2));
}

With this code you can go up to fibonacci(92) without getting long overflow miscalculations.

@danveloper
Copy link
Author

Great comment! Thank you for letting me know abou computeIfAbsent. Sorry I didn't see this sooner!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment