Skip to content

Instantly share code, notes, and snippets.

@kennycason
Created July 30, 2014 11:17
Show Gist options
  • Select an option

  • Save kennycason/f90c51fb6abb9f3a880a to your computer and use it in GitHub Desktop.

Select an option

Save kennycason/f90c51fb6abb9f3a880a to your computer and use it in GitHub Desktop.
Fibonacci's Sequence - Memoized Java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by kenny on 7/30/14.
*/
public class FibonacciTest {
private int[] mem = new int[50];
@Test
public void speedTest() {
long startTime = System.currentTimeMillis();
fib(45);
System.out.println("Unmemoized: " + (System.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
mfib(45);
System.out.println("Memoized: " + (System.currentTimeMillis() - startTime) + "ms");
}
@Test
public void equalValues() {
for(int i = 0; i < 10; i++) {
assertEquals(fib(i), mfib(i));
}
}
@Test
public void printFirst45() {
for(int i = 0; i < 45; i++) {
System.out.print(mfib(i) + ",");
}
}
public int fib(int i) {
if(i <= 1) { return 1; }
return fib(i - 1) + fib(i - 2);
}
public int mfib(int i) {
if(i <= 1) { return 1; }
if(mem[i] > 0) {
return mem[i];
}
mem[i] = mfib(i - 1) + mfib(i - 2);
return mem[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment