SlideShare a Scribd company logo
1 of 13
Download to read offline
Rekurzió,
rekurzív alprogramok
Játék (Hanoi tornyok)
Adott három oszlop. Az első oszlopon található n darab
korong, oly módón, hogy az alsó átmérője mindig nagyobb a
rajta levő korongon. Helyezzük át a korongokat a harmadikk
oszlopra a második oszlop segítségével, oly módon, hogy
mindig az alsó korong legyen nagyobb átmérőjű.
http://www.youtube.com/watch?v=aGlt2G-DC8c

N=3 esetén




          a.                   b.            c.
Példák
1. Az aranyhal és a három kívánság: az első (valami...), a
                                            első
   második (valami...), a harmadik: „teljesítsd még három
   kívánságomat”.
   kívánságomat”.
2. A matematikában, egy fogalmat rekurzív módon
   definiálunk, ha a definíción belül felhasználjuk magát a
   definiálandó fogalmat.
                 fogalmat.
   Például, a faktoriális rekurzív definícióját egy adott n szám
   esetében, a matematikus így fejezi ki:
               1,            ha n = 0
           n!= 
                n ⋅(n − 1)! ha n ∈ N*
                            ,
Rekurzió, Definició
• Egy értéket vagy egy állapotot úgy definiálunk,
  hogy definiáljuk a kezdőállapotot, majd általában
  egy állapotot az előző véges számú állapot
  segítségével határozzunk meg.




                                              Koch


   http://hu.wikipedia.org/wiki/Rekurzió
   http://hu.wikipedia.org/wiki/Koch-görbe
A rekurzió célja
• A feladat visszavezetése egy még egyszerűbb
   feladatra egészen addig amíg a feladat olyan
   egyszerű nem lesz, hogy már megoldható.
• Más szóval: a feladat megfogalmazása mindig
   ugyanaz, így az alprogram önmagát hívja de
   egyre egyszerűbb argumentummal
• Előnye: az elegancia. Néhány sorban könnyen
   érthető kódot írhatunk
• Hátránya: Akkor is használjuk ha kevéssé
   hatékony, sőt pazarló
A programozásban a rekurzió alprogramok
formájában jelenik meg, éspedig olyan
függvényeket, illetve eljárásokat nevezünk
rekurzívaknak, amelyek meghívják önmagukat.
                                    önmagukat.
 Tehát, egy alprogramot akkor nevezünk
 rekurzívnak, ha meghívja önmagát.
  Típusai:
1. Közvetlen:


2. Közvetett:
Közvetlen rekurzió
                (1)          (2)          (n)
  P                            ....
            P            P            P         ⇒ Stack
                                                  overflow

  a P eljárás         a P eljárás     a P eljárás n.
     első              második         meghívása
                      meghívása
•A P rekurzív eljárás végrehajtása következtében a
P ismételten válik aktívvá.
•Minden aktiválás eredményeként a verembe kerül
valamennyi, a hívást jelölő adat.
                            adat.
•Mivel a verem mérete véges, bizonyos számú aktiválás
                         véges,          szá
után bekövetkezhet a túlcsordulás és a program
hibaüzenettel (Stack overflow) kilép.
              (Stack overflow)
Mivel ezt a hibát feltétlenül el kell kerülnünk, a P
eljárást csak egy bizonyos feltétel ellenében
szabad újra meg újra meghívni. Legyen F az a
                          meghívni.
feltétel, amelynek igaz értéke esetén a P eljárás
meghívhatja önmagát. Az önmeghívás
legegyszerűbb
legegyszerűbb alakja:
 if F then P
                           F = true              F = true
             (1)            (2) (3)               (4) (5)
P          if F then P             if F then P      if F then P (6)
             (11)                   (9)    (8)       (7) {itt F =false}
                         (10)
    a P eljárás első            a P eljárás            a P eljárás
      aktíválása                 második               harmadik
                                aktíválása             aktíválása
Feladatok
 • Írjuk meg a n!-t kiszámító rekurzív alprogramot.
 • http://w3.enternet.hu/furedi/page2nd.html#fl_rekurzio

var n:Byte;                 Leállási feltétel

                                                kezdőállapot
  Function Fakt(n:Byte):longint;
            Fakt(n:Byte):longint;
  begin
    if n=0 then Fakt:=1
          else Fakt:=n*Fakt(n-1);
               Fakt:=n*Fakt(n-1);
                                                     előző véges
  end;                                              számú állapot

Begin
 Write('n='); ReadLn(n);
 WriteLn(n,'!=',Fakt(n));
 WriteLn(n,'!=',Fakt(n));
 ReadLn
End.
Hanoi tornyai
• Hanoi tornyai – játék
• Lépések számának meghatározása
  – Rekurzív képlet
    •   1 korong – 1 lépés
    •   2 korong – 2*lépés(1) +1 =3
    •   3 korong – 2*lépés(2) +1 =7
    •   4 korong – 2*lépés(3) +1 =15
    •   ….
    •   N korong – 2*lépés(N-1) +1
Lépések száma (explicit
             meghatározás)
Korongok száma      Lépések száma           Szabály

1                        1                   21-1
2                        3                   22-1
3                        7                   23-1
4                       15                   24-1
5                       31                   25-1
n                      ????                  2n-1
64 korong esetén, ha egy korong mozgatása 1
másodpercbe telik , akkor a korongok áthelyezése 264-1
másodperc, ami 590,000,000,000 évnek felel meg
n korongot helyezzünk át az
               Hanoi tornyok
                 első oszlopról a második
                segítségével a harmadikra.

                                              Megállási feltétel
Procedure Hanoi(n,a,b,c:integer);
Begin                            n-1 korongot helyezzünk át
 if n>0 then begin                   az első oszlopról a
                                  harmadik segítségével a
    Hanoi(n-1,a,c,b);                     másodikra.
    Writeln(n,'. korongot ',a,'. rúdról ',c,'. rúdra!');
    Hanoi(n-1,b,a,c);
 end;                            n-1 korongot helyezzünk át
                                   az második oszlopról az
End;                                  első segítségével a
                                          harmadikra.
Var n:integer;
begin
 write('a korongok szama:');
 readln(n);
 hanoi(n,1,2,3);
end.
Gyakorlatok
• http://delicious.com/kovkrly
  – Rekurzív feladatok, 2010 július 20-i bejegyzés

More Related Content

Featured

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 

Featured (20)

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 

11a

  • 2. Játék (Hanoi tornyok) Adott három oszlop. Az első oszlopon található n darab korong, oly módón, hogy az alsó átmérője mindig nagyobb a rajta levő korongon. Helyezzük át a korongokat a harmadikk oszlopra a második oszlop segítségével, oly módon, hogy mindig az alsó korong legyen nagyobb átmérőjű. http://www.youtube.com/watch?v=aGlt2G-DC8c N=3 esetén a. b. c.
  • 3. Példák 1. Az aranyhal és a három kívánság: az első (valami...), a első második (valami...), a harmadik: „teljesítsd még három kívánságomat”. kívánságomat”. 2. A matematikában, egy fogalmat rekurzív módon definiálunk, ha a definíción belül felhasználjuk magát a definiálandó fogalmat. fogalmat. Például, a faktoriális rekurzív definícióját egy adott n szám esetében, a matematikus így fejezi ki: 1, ha n = 0 n!=   n ⋅(n − 1)! ha n ∈ N* ,
  • 4. Rekurzió, Definició • Egy értéket vagy egy állapotot úgy definiálunk, hogy definiáljuk a kezdőállapotot, majd általában egy állapotot az előző véges számú állapot segítségével határozzunk meg. Koch http://hu.wikipedia.org/wiki/Rekurzió http://hu.wikipedia.org/wiki/Koch-görbe
  • 5. A rekurzió célja • A feladat visszavezetése egy még egyszerűbb feladatra egészen addig amíg a feladat olyan egyszerű nem lesz, hogy már megoldható. • Más szóval: a feladat megfogalmazása mindig ugyanaz, így az alprogram önmagát hívja de egyre egyszerűbb argumentummal • Előnye: az elegancia. Néhány sorban könnyen érthető kódot írhatunk • Hátránya: Akkor is használjuk ha kevéssé hatékony, sőt pazarló
  • 6. A programozásban a rekurzió alprogramok formájában jelenik meg, éspedig olyan függvényeket, illetve eljárásokat nevezünk rekurzívaknak, amelyek meghívják önmagukat. önmagukat. Tehát, egy alprogramot akkor nevezünk rekurzívnak, ha meghívja önmagát. Típusai: 1. Közvetlen: 2. Közvetett:
  • 7. Közvetlen rekurzió (1) (2) (n) P .... P P P ⇒ Stack overflow a P eljárás a P eljárás a P eljárás n. első második meghívása meghívása •A P rekurzív eljárás végrehajtása következtében a P ismételten válik aktívvá. •Minden aktiválás eredményeként a verembe kerül valamennyi, a hívást jelölő adat. adat. •Mivel a verem mérete véges, bizonyos számú aktiválás véges, szá után bekövetkezhet a túlcsordulás és a program hibaüzenettel (Stack overflow) kilép. (Stack overflow)
  • 8. Mivel ezt a hibát feltétlenül el kell kerülnünk, a P eljárást csak egy bizonyos feltétel ellenében szabad újra meg újra meghívni. Legyen F az a meghívni. feltétel, amelynek igaz értéke esetén a P eljárás meghívhatja önmagát. Az önmeghívás legegyszerűbb legegyszerűbb alakja: if F then P F = true F = true (1) (2) (3) (4) (5) P if F then P if F then P if F then P (6) (11) (9) (8) (7) {itt F =false} (10) a P eljárás első a P eljárás a P eljárás aktíválása második harmadik aktíválása aktíválása
  • 9. Feladatok • Írjuk meg a n!-t kiszámító rekurzív alprogramot. • http://w3.enternet.hu/furedi/page2nd.html#fl_rekurzio var n:Byte; Leállási feltétel kezdőállapot Function Fakt(n:Byte):longint; Fakt(n:Byte):longint; begin if n=0 then Fakt:=1 else Fakt:=n*Fakt(n-1); Fakt:=n*Fakt(n-1); előző véges end; számú állapot Begin Write('n='); ReadLn(n); WriteLn(n,'!=',Fakt(n)); WriteLn(n,'!=',Fakt(n)); ReadLn End.
  • 10. Hanoi tornyai • Hanoi tornyai – játék • Lépések számának meghatározása – Rekurzív képlet • 1 korong – 1 lépés • 2 korong – 2*lépés(1) +1 =3 • 3 korong – 2*lépés(2) +1 =7 • 4 korong – 2*lépés(3) +1 =15 • …. • N korong – 2*lépés(N-1) +1
  • 11. Lépések száma (explicit meghatározás) Korongok száma Lépések száma Szabály 1 1 21-1 2 3 22-1 3 7 23-1 4 15 24-1 5 31 25-1 n ???? 2n-1 64 korong esetén, ha egy korong mozgatása 1 másodpercbe telik , akkor a korongok áthelyezése 264-1 másodperc, ami 590,000,000,000 évnek felel meg
  • 12. n korongot helyezzünk át az Hanoi tornyok első oszlopról a második segítségével a harmadikra. Megállási feltétel Procedure Hanoi(n,a,b,c:integer); Begin n-1 korongot helyezzünk át if n>0 then begin az első oszlopról a harmadik segítségével a Hanoi(n-1,a,c,b); másodikra. Writeln(n,'. korongot ',a,'. rúdról ',c,'. rúdra!'); Hanoi(n-1,b,a,c); end; n-1 korongot helyezzünk át az második oszlopról az End; első segítségével a harmadikra. Var n:integer; begin write('a korongok szama:'); readln(n); hanoi(n,1,2,3); end.
  • 13. Gyakorlatok • http://delicious.com/kovkrly – Rekurzív feladatok, 2010 július 20-i bejegyzés