diff --git a/src/main/java/src/TasksFrame.java b/src/main/java/src/TasksFrame.java index 9d32072..b3e75c6 100644 --- a/src/main/java/src/TasksFrame.java +++ b/src/main/java/src/TasksFrame.java @@ -64,6 +64,8 @@ public class TasksFrame extends JFrame { public void run() { + setupFib(); + setupHelloWorld(); setupDate(); @@ -107,7 +109,59 @@ public class TasksFrame extends JFrame { setupBmi(); setupReverse(); + } + + private void setupFib() { + JPanel jPanel = setupPanel("Fibonacci"); + + JTextField input = new JTextField(); + input.setBounds(5, 60, 50, 30); + input.setVisible(true); + jPanel.add(input); + JTextField output = new JTextField(); + output.setBounds(5, 100, 200, 30); + output.setVisible(true); + jPanel.add(output); + + JButton button = new JButton("Calculate Fibonacci"); + button.setBounds(70, 60, 150, 30); + button.setVisible(true); + jPanel.add(button); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.setText(""); + Integer n = Integer.valueOf(input.getText()); + int[] a = new int[n+1]; + recursiveFibonacci(a, n); + + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < a.length; i++) { + stringBuffer.append(a[i]); + if (i==a.length-1) { + stringBuffer.append(""); + } else { + stringBuffer.append(", "); + } + } + output.setText(stringBuffer.toString()); + } + }); + } + + public int recursiveFibonacci(int[] a, int n) { + if (n == 0) { + a[n] = 0; + return 0; + } else if (n == 1) { + a[n] = 1; + return 1; + } else { + int i = recursiveFibonacci(a, n - 1) + recursiveFibonacci(a, n-2); + a[n] = i; + return a[n]; + } } private void setupReverse() { diff --git a/src/test/java/src/TasksFrameTest.java b/src/test/java/src/TasksFrameTest.java index c99c3db..19358f6 100644 --- a/src/test/java/src/TasksFrameTest.java +++ b/src/test/java/src/TasksFrameTest.java @@ -7,6 +7,15 @@ import static org.junit.jupiter.api.Assertions.*; class TasksFrameTest { + @Test + void test_recursiveFib() { + TasksFrame tasksFrame = new TasksFrame(); + int[] ints = new int[10 + 1]; + tasksFrame.recursiveFibonacci(ints, 10); + + assertArrayEquals(new int[]{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55}, ints); + } + @Test void bin1() { TasksFrame tasksFrame = new TasksFrame();