Fungsi Rekursif
Fungsi Rekursif Definisi fungsi rekursif. Contoh 1 : Faktorial Contoh 2 : Perkalian Contoh 3 : Fibonacci Contoh 4 : Tower of Hanoi
Fungsi Rekursif Fungsi biasa dipanggil oleh fungsi lain. Sedangkan fungsi rekursif dipanggil oleh dirinya sendiri. A B C D A A A A
Fungsi Rekursif Setara dengan proses looping/ iterasi faktorial, perkalian Kadang rekursif lebih baik dari iterasi tower of hanoi Terkadang sebaliknya fibonacci Komponen : Way out if – else + return() Recursive call dengan value baru
Simple Example def endless puts “Never end” endless() return 0 end
Faktorial ALGORITMA n! = 1 if n == 0 n! = n * ( n – 1 )! if n > 0 4! = 4 x 3! 3! = 3 x 2! 2! = 2 x 1! 1! = 1 x 0! 0! = 1 SOURCE CODE def factorial(n) if n==0 then return 1 end x=n-1 y=factorial(x) return (n*y) puts factorial(5)
Latihan tracing rekursi
Perkalian ALGORITMA a * b = a if b == 1 a * b = a * ( b – 1 ) + a if b > 1 6 x 3 = ( 6 x 2 ) + 6 = ( 6 x 1 ) + 6 + 6 = 6 + 6 + 6 = 18 SOURCE CODE def mult(a,b) if b==1 then return a end c=b-1 d=mult(a,c) sum=d+a return (sum) puts mult(3,4) puts mult(5,8)
Latihan tracing rekursi
Fibonacci The Fibonacci series fn≥0 is a famous series defined by: f0 :≡ 0, f1 :≡ 1, fn≥2 :≡ fn−1 + fn−2 f2 = f0 + f1 = 0 + 1 = 1 f3 = f1 + f2 = 1 + 1 = 2 f4 = f2 + f3 = 1 + 2 = 3 f5 = f3 + f4 = 2 + 3 = 5 …. Leonardo Fibonacci 1170-1250
Fibonacci ALGORITMA fibo( n ) = n if n == 0 or n == 1 fibo( n ) = fibo(n – 2) + fibo( n – 1 ) if n >= 2 fibo( 4 ) = fibo( 3 ) + fibo( 2 ) = fibo( 2 ) + fibo ( 1 ) + fibo( 2 ) = fibo(1) + fibo(0) + fibo(1) + fibo(2) = 1 + fibo(0) + fibo(1) + fibo(2) = 1 + 0 + fibo(1) + fibo(2) = 1 + fibo(1) + fibo(2) = 1 + 1 + fibo(2) = 2 + fibo(2) = 2 + fibo(1) + fibo(0) = 2 + 1 + fibo(0) = 2 + 1 + 0 = 2 + 1 = 3 SOURCE CODE def fibo(n) if n<=1 then return n end x=fibo(n-1) y=fibo(n-2) return (x+y) puts fibo(4) puts fibo(8)
Tracing Fibonacci fibo (4) = ? F(4) 2+1=3 1+0=1 1+1=2 F(2) F(1) F(0) 1+0=1 1 F(1) F(2) F(1) F(0) 1
Towers of Hanoi ALGORITMA If n == 1, move the single disk from A to C and stop. Move the top n – 1 disks from A to B, using C as auxiliary. Move the remaining disk from A to C. Move the n – 1 disks from B to C, using A as auxiliary. SOURCE CODE def towers(n,from,to,aux) if n==1 then puts "move disk 1 from #{from} to #{to}" return end towers(n-1,from,aux,to) puts "move disk #{n} from #{from} to #{to}" towers(n-1,aux,to,from) towers(3,'A','C','B') #call method towers with 4 parameters
Tracing Towers of Hanoi towers(3, A, C, B) = ?
Tugas : TRACING towers(4, A, C, B) = ? fibo(6) = ? factorial(5)=? mult(3,5)=?