- Find the largest number from the input
- Generate a necessary fibonaci numbers
- Walk through all elements in the input and find the next fibonacci number
public class NextFibonacciGenerator {
public void nextFibonacci(int[] input) {
int[] results = generateNextFibonacciNumbers(input);
for (int num : results) {
System.out.println(num);
}
}
int[] generateNextFibonacciNumbers(int[] input) {
List<Integer> fibs = generateFibonacciNumbersOverTarget(getLargestNumber(input));
int[] result = new int[input.length];
for (int i = 0; i < input.length; i++) {
result[i] = getNextFibonacciNumber(fibs, input[i]);
}
return result;
}
private List<Integer> generateFibonacciNumbersOverTarget(int target) {
List<Integer> result = new ArrayList<>(Arrays.asList(1, 1));
if (target < 1) {
return result;
}
for (int i = 2;; i++) {
int current = result.get(i - 1) + result.get(i - 2);
result.add(current);
if (current > target) {
return result;
}
}
}
private int getLargestNumber(int[] input) {
int largestNumber = Integer.MIN_VALUE;
for (int number : input) {
if (number > largestNumber) {
largestNumber = number;
}
}
return largestNumber;
}
private int getNextFibonacciNumber(List<Integer> fibs, int target) {
for (int fib : fibs) {
if (fib > target) {
return fib;
}
}
throw new IllegalArgumentException(
"The target shouldn't be bigger than all generated fibonacci numbers"
);
}
}
@RunWith(value = Parameterized.class)
public class NextFibonacciGeneratorTest {
@Parameterized.Parameters
public static List<Object []> data() {
return Arrays.asList(new Object[][] {
{new int[]{2, 13, 34, 13}, new int[]{1, 9, 22, 11}},
{new int[]{89, 55, 13, 34}, new int[]{81, 40, 11, 33}},
{new int[]{144, 8, 13, 3, 55}, new int[]{100, 7, 10, 2, 50}},
{new int[]{2, 2, 13, 13}, new int[]{1, 1, 8, 8}}
});
}
private int[] expectation;
private int[] input;
public NextFibonacciGeneratorTest(int[] expectation, int[] input) {
this.expectation = expectation;
this.input = input;
}
@Test
public void When_InputIsEmpty_Should_ReturnEmpty() {
// Arrange
NextFibonacciGenerator testee = createGenerator();
int[] input = new int[0];
// Action
int[] result = testee.generateNextFibonacciNumbers(input);
// Assert
Assert.assertEquals(0, result.length);
}
@Test
public void When_InputWithValues_Should_ReturnNextFibonacciNumber() {
// Arrange
NextFibonacciGenerator testee = createGenerator();
// Action
int[] result = testee.generateNextFibonacciNumbers(input);
// Assert
Assert.assertArrayEquals(expectation, result);
}
private NextFibonacciGenerator createGenerator() {
return new NextFibonacciGenerator();
}
}