-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFiboRec.java
65 lines (55 loc) · 1.32 KB
/
FiboRec.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
import plotter.Graphic;
import plotter.LineStyle;
import plotter.Plotter;
import plotter.Sleep;
/**
* Visualization of the recursive calculation of the Fibonacci numbers.
* Two versions - with and without memoization - are called.
*
* @author Stephan Euler
* @version June 2015
*/
public class FiboRec {
static Graphic graphic;
static Plotter plotter;
static Map<Integer, Long> memory = new HashMap<Integer, Long>();
static {
graphic = new Graphic("Fibonacci rekursiv");
plotter = graphic.getPlotter();
plotter.setDataLineStyle(LineStyle.VALUE);
plotter.setDataColor(Color.BLUE);
memory.put( 0, 0l );
memory.put( 1, 1l );
}
/**
* @param args
*/
public static void main(String[] args) {
int n = 10;
plotter.setStatusLine("call trace for fibo(" + n + ")");
fibo( n);
plotter.nextVector();
plotter.setDataColor(Color.BLACK);
fiboMem( n );
}
public static long fibo(int n) {
plotter.add(n);
Sleep.sleep(30);
plotter.repaint();
if (n == 1 | n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
public static long fiboMem(int n) {
plotter.add(n);
Sleep.sleep(30);
plotter.repaint();
if( ! memory.containsKey(n) ) {
memory.put(n, fiboMem(n - 1) + fiboMem(n - 2));
}
return memory.get(n);
}
}