compsci 201 201 recursio sion d dna lin ink p previe iew
play

Compsci 201 201 Recursio sion, D DNA-Lin ink P Previe iew - PowerPoint PPT Presentation

Compsci 201 201 Recursio sion, D DNA-Lin ink P Previe iew Susan Rodger February 28, 2020 2/28/2020 Compsci 201, Spring 2020 1 Announcements Exa Exam 1 1 Ask f for R Reg egrade in in Gradesco cope by by March 1 1


  1. Compsci 201 201 Recursio sion, D DNA-Lin ink P Previe iew Susan Rodger February 28, 2020 2/28/2020 Compsci 201, Spring 2020 1

  2. Announcements • Exa Exam 1 1 – Ask f for R Reg egrade in in Gradesco cope by by March 1 1 • Regrades a assig ignm nment ents • if you pushed to github but did not resubmit in gradescope, fill out regrade form and we can look at your github if you have not modified it! • Assig ignm nment nt P P3 las ast c chanc ance t e today o on time • Assig ignm nment nt P P4 out to today wit ith a h a Par art1 and and P Par art2 • Part 1 due March 5, Part 2 due March 19 • APT T 4 4 due T ue Tue uesday! • APT APT Quiz iz 1 – now on on regular ular APT APT pag age • Not for credit, but finish if you didn’t 2/28/2020 Compsci 201, Spring 2020 2

  3. N is for … • new • Allocating memory from the heap • null • Value when nothing has been allocated 2/28/2020 Compsci 201, Spring 2020 3

  4. PFtLFiF • Introduct uctio ion t n to Recur cursio ion • Canonical problem-solving/programming tool • Useful for lists, trees, and when structure is self- referential (algorithmic too, not today) • Review link linked lis lists in in cont ntext o of P4: D 4: DNA-link ink • You can work with a partner from your Discussion section • Choose next week, run code, finish after break 2/28/2020 Compsci 201, Spring 2020 4

  5. Modify and Return linked list • If we e pass a a poin inter t to fir irst no node and and .. .. • Want to "remove first" • We must return a pointer to modified list • void change(ListNode first) • Call change(list) • first = first.next • list not changed after call first 2/28/2020 Compsci 201, Spring 2020 5

  6. What does pass-by-value mean? • Java p passes es p param ameter ers b by va value ue • Pass a copy of the variable • A copy of list1 is passed 2/28/2020 Compsci 201, Spring 2020 7

  7. Idiom: pass-and-return • Cha hange t the lis he list p passed in, in, r return t the he lis list. • Assign in the call, e.g. x = changeUp(x) Thing xx = new Thing(); change(xx); // can xx be different after call? // can write xx.mutate() // cannot assign to xx in change xx = changeUp(xx); 2/28/2020 Compsci 201, Spring 2020 8

  8. Invariants • Class l level el: t : true ue b bef efore e e each m ch met etho hod e execut ecutes • Established at construction • Re-established by each method • Loop level el: t true b ue bef efore e e each l ch loop guar ard e eval alua uatio ion • Established before first iteration of loop • Re-established after each loop iteration • Rea eason f formally and and inf informally ab about ut co code 2/28/2020 Compsci 201, Spring 2020 10

  9. WOTO http:// //bi bit.ly/2 /201spr pring20-02 0226 26-2 2/28/2020 Compsci 201, Spring 2020 11

  10. Google (DYM): Recursion • What i is the e Inter erne net? • A network of networks …. • What i is PageR eRank nk? • What’s a good website link? public int calc(int n){ return n*calc(n-1); } 2/28/2020 Compsci 201, Spring 2020 12

  11. Self Reference and Recursion • Does a a Node r ref eferenc nce i e itself lf? • No, there’s a .next field, but … • Does a a recur cursiv ive m metho hod c call i l itself elf? • No, calls clones of itself • Careful, could make “infinite” number of calls … • Wha hat’s in in a a fold lder? • Files and other folders. Is that self-referential? 2/28/2020 Compsci 201, Spring 2020 13

  12. Google recursion Did you mean …? • Tho Those s software eng engin ineers … • Did you mean invented by Noam Shazeer, Duke 1998: Math and Compsci 2/28/2020 Compsci 201, Spring 2020 14

  13. Noam Shazeer, Duke 2008 https://www.newyorker er.com/magaz azin ine/ e/20 2018/ 18/12/ 12/10/ 10/the-frien endship ip-that-ma made-goog oogle-hug uge • • Compsc sci 201 a alu lum, p pas assio iona nate a about ut p problem lem- solving ing 2/28/2020 Compsci 201, Spring 2020 15

  14. When to use recursion • The The structure o of the p he problem lend lends it itself lf … • Folders/Directories contain … • Nodes in a linked list contain … • The alg The algorithmic structure lend lends it itself … … • Sorting algorithms as we’ll see … • Factorial? Just say no … 2/28/2020 Compsci 201, Spring 2020 16

  15. Size of a linked list • You' u've s see een a a lo loop t to do this his • Goal al: t try t to und understand why hy thi his is is correct • We'll u ll use e example le from a arit ithm hmetic t ic too • Vocabula ulary w with b h both struc uctur ure a e and a algorit ithm hm 2/28/2020 Compsci 201, Spring 2020 17

  16. Vocabulary • All ll rec ecursive c code e ha has a a base case • A simple case where no recursion necessary • Example in linked list? null, no recursion • sometimes one node case too • Base c case alw always id iden entif ified w wit ith h an an if if statement. 2/28/2020 Compsci 201, Spring 2020 18

  17. Understanding Recursion • Visua uali lize: : RecDe Demo mo.java • The base case anchors the recursion https://c ://coursework.cs.d .duke.e .edu/201 /201spring20/c 0/classcode/b /blob/m /master/s /src/R /RecDe Demo.j .java • Ther There's no no lo loop! W Why hy? • Sequence of recursive calls • Stacked up until base returns • The r The rec ecursive c call all "d "decreases" • Must get toward bas ase c e cas ase 2/28/2020 Compsci 201, Spring 2020 19

  18. RecDemo.java 2/28/2020 Compsci 201, Spring 2020 20

  19. RecDemo.java – rest of it 2/28/2020 Compsci 201, Spring 2020 21

  20. About to count # nodes in list • Call ll create(4) finis ished hed, c , call ll count(list) • What does list point to ? list.next ? 2/28/2020 Compsci 201, Spring 2020 22

  21. First recursive call made • Each h metho hod o on the s e stack ck/pile o ile of met etho hods h has as its own local s al state: w : what at d does l list r refer erence ence? • Node 3 in doit/first call, node 2 in recursive call 2/28/2020 Compsci 201, Spring 2020 23

  22. Second recursive call made • Three ee c calls lls o of count nt m made: w : where i e is act ctiv ive c e call? ll? • Parameter list points at 1, what happens? 2/28/2020 Compsci 201, Spring 2020 24

  23. What do we see? • Each m h metho hod invocatio ion n has i its ts o own sta tate: param ameter, l local al varia iable les, l , line n number er • Goal: t : trus ust r recur ursio ion • Trust is hard • Debugging on trust? Not so easy 2/28/2020 Compsci 201, Spring 2020 25

  24. Last call: base case reached • The ac The active c cal all l ha has lis list = == null null • Base case reached! Return 0 • Where i e is t this v value ue r ret etur urned ned? • To the call: the stack frame "above" • Addit ition hap happens b bac ack up up call all-cha hain in 2/28/2020 Compsci 201, Spring 2020 26

  25. How did recursion work? • Structure o of a a link linked lis list is is es essential • For a non-null list, # nodes is: count me, and recursively count the rest, add together • Rec ecursion in in gene eneral: p process o one c ne case, o one ne number, o , one n node. M Make a a recur ursiv ive c call ll, u use e result ult. • Code must use return value of recursive call • For lists? Deal with one node only in code 2/28/2020 Compsci 201, Spring 2020 27

  26. How do you calculate N! • Mul ultip iply 1 x 1 x 2 x 2 x 3 x 3 x … x N x N public int fact(int n){ int prod = 1; for(int k=2; k <= n; k++){ prod *= k; } return prod; } 2/28/2020 Compsci 201, Spring 2020 28

  27. Recursive Terminology • Recursi sive m meth thods m s must h st have a a bas ase c e cas ase • Simple to do, don’t need “help” • Recur cursiv ive c calls ls m make p progress t towar ard bas ase c e case • Some measure gets smaller, toward base case • Wha hat’s n! n! • It’s n * (n-1)! • What’s the base case? 1! Is 1 (or 0! Is 1) 2/28/2020 Compsci 201, Spring 2020 29

  28. Don ’ t do this! n=4 • int int x = f = fact(4 (4); ); public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); • return 4*fact(3) } • The c The cal all o of fac act(3) c cal alls a a “clo lone” o or “copy” • Doesn’t call “itself”, is re re-ent entrant ant c code public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); } 2/28/2020 Compsci 201, Spring 2020 30

  29. Don ’ t do this 2 n=4 • int int x = f = fact(4 (4); ); public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); • return 4*fact(3) } n=3 public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); } public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); } 2/28/2020 Compsci 201, Spring 2020 31

  30. Don ’ t do this 3 n=4 • int int x = f = fact(4 (4); ); public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); • return 4*fact(3) } n=3 • retur urn n 3 * * f fact ct(2) 2) public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); } n=2 public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); } 2/28/2020 Compsci 201, Spring 2020 32

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend