Skip to content

Instantly share code, notes, and snippets.

@biboudis
Created December 15, 2011 16:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biboudis/1481686 to your computer and use it in GitHub Desktop.
Save biboudis/1481686 to your computer and use it in GitHub Desktop.
A simple memoization with AspectJ, for golden ratio calculation.
package tests.recursive;
public class GoldenRation {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static double goldenratio(int n){
return fib(n+1)*Math.pow(fib(n),-1);
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 2; i <= N; i++)
System.out.println(i + ": " + goldenratio(i));
}
}
package tests.recursive;
import java.util.HashMap;
public aspect MemoizeAspect {
HashMap<Integer, Long> mem = new HashMap<Integer, Long>();
pointcut RecPointcut(Integer num) : execution (long fib(*)) && args(num);
long around (Integer num) : RecPointcut(num)
{
long ret;
if(mem.containsKey(num))
ret = mem.get(num);
else
{
ret = proceed(num);
mem.put(num, ret);
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment