Browse Source

recursive fibonacci implemented in TasksFrame

main
fdai6499 2 years ago
parent
commit
85d338bf94
  1. 54
      src/main/java/src/TasksFrame.java
  2. 9
      src/test/java/src/TasksFrameTest.java

54
src/main/java/src/TasksFrame.java

@ -64,6 +64,8 @@ public class TasksFrame extends JFrame {
public void run() { public void run() {
setupFib();
setupHelloWorld(); setupHelloWorld();
setupDate(); setupDate();
@ -107,7 +109,59 @@ public class TasksFrame extends JFrame {
setupBmi(); setupBmi();
setupReverse(); 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() { private void setupReverse() {

9
src/test/java/src/TasksFrameTest.java

@ -7,6 +7,15 @@ import static org.junit.jupiter.api.Assertions.*;
class TasksFrameTest { 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 @Test
void bin1() { void bin1() {
TasksFrame tasksFrame = new TasksFrame(); TasksFrame tasksFrame = new TasksFrame();

Loading…
Cancel
Save