Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách triển khai dãy Fibonacci trong JShell Java 9

JShell (Java 9 REPL) cho phép thực thi code Java và in kết quả ngay. Dãy Fibonacci: số tiếp theo = tổng 2 số trước (0, 1, 1, 2, 3, 5, 8...).

Ví dụ trong JShell

C:\Users\User> jshell
| Welcome to JShell -- Version 9.0.4
jshell> int x=0, y=1, z=0, count=5;
x ==> 0
y ==> 1
z ==> 0
count ==> 5
jshell> {
   ...>     System.out.println(x+"\n"+y);
   ...>     for(int i=0; i<count; i++) {
   ...>         x=y; y=z;
   ...>         z = x+y;
   ...>         System.out.println(z);
   ...>     }
   ...> }
0
1
1
2
3
5
8

Các cách khác trong JShell

Dùng Stream.iterate (Java 9+)

jshell> Stream.iterate(new int[]{0,1}, t -> new int[]{t[1], t[0]+t[1]})
   ...>     .limit(10)
   ...>     .map(t -> t[0])
   ...>     .forEach(System.out::println)
0
1
1
2
3
5
8
13
21
34

Dùng phương thức helper

jshell> List<Integer> fib(int n) {
   ...>     List<Integer> list = new ArrayList<>();
   ...>     int a=0, b=1;
   ...>     for(int i=0; i<n; i++) {
   ...>         list.add(a);
   ...>         int temp = a+b; a=b; b=temp;
   ...>     }
   ...>     return list;
   ...> }
jshell> fib(10)
$1 ==> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

JShell lý tưởng để thử nghiệm thuật toán, đệ quy, stream mà không cần boilerplate class/main.