Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/main/java/io/zipcoder/Problem2.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,41 @@
package io.zipcoder;

import java.util.ArrayList;
import java.util.Collections;

public class Problem2 {

public String fibonacci(int n) {

ArrayList<Integer> fib = new ArrayList<Integer>();
fib.add(0);
fib.add(1);
int i = 1;
while (fib.get(i) < n) {
if (fib.get(i - 1) + fib.get(i) > n)
break;
else fib.add(fib.get(i - 1) + fib.get(i));
i++;
}
String result = fib.get(0) + "";
for (int j = 1; j < fib.size(); j++)
result += ", " + fib.get(j);

return result;
}

public String getRecursive(int n) {
String result = "0, ";

result += fib2(0, 1, n);
return result;
}

public String fib2(int prev, int current, int n) {
if (current + prev < n)
return current + ", " + fib2(current, current + prev, n);

return "" + current;
}

}
29 changes: 29 additions & 0 deletions src/test/java/io/zipcoder/Problem2Test.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,33 @@
package io.zipcoder;

import org.junit.Assert;
import org.junit.Test;

public class Problem2Test {

Problem2 problem2=new Problem2();

@Test
public void fibonacciTest(){
String expected="0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144";
String actual=problem2.fibonacci(150);

Assert.assertEquals(expected, actual);
}

@Test
public void fib2Test(){
String expected="1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144";
String actual=problem2.fib2(0,1,150);

Assert.assertEquals(expected, actual);
}

@Test
public void getRecursiveTest(){
String expected="0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144";
String actual=problem2.getRecursive(150);

Assert.assertEquals(expected, actual);
}
}