Presentasi sedang didownload. Silahkan tunggu

Presentasi sedang didownload. Silahkan tunggu

 Definisi fungsi rekursif.  Contoh 1 : Faktorial  Contoh 2 : Perkalian  Contoh 3 : Fibonacci  Contoh 4 : Tower of Hanoi.

Presentasi serupa


Presentasi berjudul: " Definisi fungsi rekursif.  Contoh 1 : Faktorial  Contoh 2 : Perkalian  Contoh 3 : Fibonacci  Contoh 4 : Tower of Hanoi."— Transcript presentasi:

1

2  Definisi fungsi rekursif.  Contoh 1 : Faktorial  Contoh 2 : Perkalian  Contoh 3 : Fibonacci  Contoh 4 : Tower of Hanoi

3

4  Fungsi biasa dipanggil oleh fungsi lain. Sedangkan fungsi rekursif dipanggil oleh dirinya sendiri. ABCD AAA A

5  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

6 def endless puts “Never end” endless() return 0 end

7 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) end puts factorial(5)

8

9 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 ) = = 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) end puts mult(3,4) puts mult(5,8)

10

11  The Fibonacci series f n≥0 is a famous series defined by: f 0 :≡ 0, f 1 :≡ 1, f n≥2 :≡ f n−1 + f n−2  f 2 = f 0 + f 1 = = 1  f 3 = f 1 + f 2 = = 2  f 4 = f 2 + f 3 = = 3  f 5 = f 3 + f 4 = = 5  …. Leonardo Fibonacci

12 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) = fibo(1) + fibo(2) = 1 + fibo(1) + fibo(2) = fibo(2) = 2 + fibo(2) = 2 + fibo(1) + fibo(0) = fibo(0) = = = 3 SOURCE CODE def fibo(n) if n<=1 then return n end x=fibo(n-1) y=fibo(n-2) return (x+y) end puts fibo(4) puts fibo(8)

13  fibo (4) = ? F(4) F(2) F(1)F(0) F(3) F(1) F(2) F(1)F(0) =11 1+1= =1 2+1=3

14 ALGORITMA 1.If n == 1, move the single disk from A to C and stop. 2.Move the top n – 1 disks from A to B, using C as auxiliary. 3.Move the remaining disk from A to C. 4.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) end towers(3,'A','C','B') #call method towers with 4 parameters

15  towers(3, A, C, B) = ?

16  towers(4, A, C, B) = ?  fibo(6) = ?  factorial(5)=?  mult(3,5)=?


Download ppt " Definisi fungsi rekursif.  Contoh 1 : Faktorial  Contoh 2 : Perkalian  Contoh 3 : Fibonacci  Contoh 4 : Tower of Hanoi."

Presentasi serupa


Iklan oleh Google