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
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

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

2/28/2020 Compsci 201, Spring 2020 1

Susan Rodger February 28, 2020

slide-2
SLIDE 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

  • n 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

  • n regular

ular APT APT pag age

  • Not for credit, but finish if you didn’t

2/28/2020 Compsci 201, Spring 2020 2

slide-3
SLIDE 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

slide-4
SLIDE 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

  • f 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

slide-5
SLIDE 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

2/28/2020 Compsci 201, Spring 2020 5

first

slide-6
SLIDE 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

slide-7
SLIDE 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)

2/28/2020 Compsci 201, Spring 2020 8

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);

slide-8
SLIDE 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

slide-9
SLIDE 9

WOTO

http:// //bi bit.ly/2 /201spr pring20-02 0226 26-2

2/28/2020 Compsci 201, Spring 2020 11

slide-10
SLIDE 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?

2/28/2020 Compsci 201, Spring 2020 12

public int calc(int n){ return n*calc(n-1); }

slide-11
SLIDE 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

slide-12
SLIDE 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

slide-13
SLIDE 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

  • ogle-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

slide-14
SLIDE 14

When to use recursion

  • The

The structure o

  • f 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

slide-15
SLIDE 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

slide-16
SLIDE 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

slide-17
SLIDE 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

slide-18
SLIDE 18

RecDemo.java

2/28/2020 Compsci 201, Spring 2020 20

slide-19
SLIDE 19

RecDemo.java – rest of it

2/28/2020 Compsci 201, Spring 2020 21

slide-20
SLIDE 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

slide-21
SLIDE 21

First recursive call made

  • Each

h metho hod o

  • n the s

e stack ck/pile o ile of met etho hods h has as its

  • wn 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

slide-22
SLIDE 22

Second recursive call made

  • Three

ee c calls lls o

  • f 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

slide-23
SLIDE 23

What do we see?

2/28/2020 Compsci 201, Spring 2020 25

  • Each m

h metho hod invocatio ion n has i its ts o

  • wn 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

slide-24
SLIDE 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

slide-25
SLIDE 25

How did recursion work?

  • Structure o
  • f 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

  • ne c

ne case, o

  • ne

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

slide-26
SLIDE 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

2/28/2020 Compsci 201, Spring 2020 28

public int fact(int n){ int prod = 1; for(int k=2; k <= n; k++){ prod *= k; } return prod; }

slide-27
SLIDE 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

slide-28
SLIDE 28

Don’t do this!

  • int

int x = f = fact(4 (4); );

  • return 4*fact(3)
  • The c

The cal all o

  • f fac

act(3) c cal alls a a “clo lone” o

  • r “copy”
  • Doesn’t call “itself”, is re

re-ent entrant ant c code

2/28/2020 Compsci 201, Spring 2020 30

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); }

n=4

slide-29
SLIDE 29

Don’t do this 2

  • int

int x = f = fact(4 (4); );

  • return 4*fact(3)

2/28/2020 Compsci 201, Spring 2020 31

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); }

n=4

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=3

slide-30
SLIDE 30

Don’t do this 3

  • int

int x = f = fact(4 (4); );

  • return 4*fact(3)
  • retur

urn n 3 * * f fact ct(2) 2)

2/28/2020 Compsci 201, Spring 2020 32

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=4

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=3

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=2

slide-31
SLIDE 31

Don’t do this 3

  • int

int x = f = fact(4 (4); );

  • return 4*fact(3)
  • retur

urn n 3 * * f fact ct(2) 2)

  • When

hen n n is is 2 2 …?

  • return 2 * fact(1)

2/28/2020 Compsci 201, Spring 2020 33

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=4

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=3

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=2

slide-32
SLIDE 32

Base Case Reached

  • retur

urn 2 n 2*fact act(1) 1)

  • Evaluates to 2*1
  • Return to call of fact(1)

2/28/2020 Compsci 201, Spring 2020 34

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=4

public int fact(int n){ if (n == 1) return 1; return n*fact(n-1); }

n=3

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); }

n=1

slide-33
SLIDE 33

WOTO

http:// //bi bit.ly/2 /201spr pring20-02 0228 28-1

2/28/2020 Compsci 201, Spring 2020 36

slide-34
SLIDE 34

From Links to …

2/28/2020 Compsci 201, Spring 2020 37

  • What

at i is the e P4: P4: D DNA NA/Lin inkS kStr trand assig ignme ment a t about? t?

  • Why do we study linked lists
  • How do you work in a group?
  • Two people from the same Discussion section

Kary Mullis

slide-35
SLIDE 35

From PCR to linked lists

  • Poly

lymerase C e Chain R in React ctio ion

  • Make copies of a specific DNA segment
  • Reco

combina inant nt D DNA

  • Insert DNA using restriction enzymes
  • Loosel

ely f forms b basis is f for D DNA/Link inked ed as assig ignm nment ent

  • Big gains in efficiency using Linked Lists
  • Compare to array of chars, e.g. Strings

2/28/2020 Compsci 201, Spring 2020 38

slide-36
SLIDE 36

But first! Let's look at strings…

  • See

e String ingPla lay.java

  • https://coursework.cs.duke.edu/201spring20/classcode/blob/master/src/St

ringPlay.java

  • Runtime of stringConcat(“hello”,N)
  • Depends on size of ret: 5, 10, 15, … 5*N
  • 5(1 + 2 + … + N) which is O(N2)

2/28/2020 Compsci 201, Spring 2020 39

public String stringConcat(String s, int reps) { String ret = ""; for(int k=0; k < reps; k++) { ret += s; } return ret; }

slide-37
SLIDE 37

StringBuilder Examined

  • Jus

ust s say no no to quad uadratic, us use String ingBuild uilder er

  • String is immutable, StringBuilder is not
  • Run

untim ime o

  • f builderConcat(“hello”,N)
  • 5 + 5 + 5 + … + 5 a total of N times: O(N)

2/28/2020 Compsci 201, Spring 2020 40

public String builderConcat(String s, int reps) { StringBuilder ret = new StringBuilder(); for(int k=0; k < reps; k++) { ret.append(s); } return ret.toString(); }

slide-38
SLIDE 38

Summary of Concatenation

  • Using s

s + t t for t two s str trings

  • Takes time s.length() + t.length()
  • Makes a new string, doesn't change s or t
  • Using

g String ingBuild uilder er is more ef efficient icient

  • Time for s.append(t) is t.length()
  • Why? Just add t.length() characters to s –

backed by array in s

2/28/2020 Compsci 201, Spring 2020 41

slide-39
SLIDE 39

Output from StringPlay

  • Which is O

s O(N) a and w which is O s O(N2) size string size builder

50000 0.169. 50000 0.000 100000 0.314 100000 0.000 150000 0.533 150000 0.001 200000 0.784 200000 0.001 250000 1.341 250000 0.001 300000 1.769 300000 0.002 350000 2.496 350000 0.001 400000 3.326 400000 0.001 450000 4.371 450000 0.001 500000 5.437 500000 0.001

2/28/2020 Compsci 201, Spring 2020 42

slide-40
SLIDE 40

WOTO

http:// //bi bit.ly/2 /201spr pring20-02 0228 28-2

2/28/2020 Compsci 201, Spring 2020 43

slide-41
SLIDE 41

danah boyd

Dr.

  • r. danah

ah boyd is a a Senior R Resear earcher er at at Microso soft R Rese search, … … a Visiting P Professo ssor at t NYU, …H …Her w work e rk examines e every ryday practic ices i involv lving ing social m l media ia, w with h specif ific ic a attent ntion t n to youth h engagement nt, privacy, a and nd ris isky beha

  • haviors. S

She he r recently wro rote te Engag aging t the E e Ethics of Dat ata S a Scien ence e in P Prac actice; c coau authored ed Isomo morphism m throug ugh a h algorit ithm hms: I Instit itut utio iona nal l Depen enden encies es i in the c e cas ase of Facebook

2/28/2020 Compsci 201, Spring 2020 44

"Building new connections is a critical part of building a new

  • economy. The American education system, as flawed as it is, is

great for the creative class because of the way it mixes up networks."

slide-42
SLIDE 42

DNA Cut and Splice

  • Find

ind enz enzyme lik like ‘ ‘gat’

  • Replace with splicee like ‘gggtttaaa’
  • Stri

rings gs a and String ingBuild uilder er fo for c creating n g new s stri rings

  • Complexity of “hello” + “world”, or A+B
  • String: A + B, StringBuilder: B

2/28/2020 Compsci 201, Spring 2020 45

slide-43
SLIDE 43

What do linked lists get us?

  • Faster r

run-tim ime, m much b h better u use o e of memory

  • We splice in constant time? Re-use strings
  • Same as previous slide: sequential char view

2/28/2020 Compsci 201, Spring 2020 46

slide-44
SLIDE 44

linked list improvement: memory

  • Suppose w

e we have B B "gat" ( (blue lue), i , in strand nd s siz ize N N

  • Inserting size S "gggtttaaa" (green) splicees
  • For String/StringBuilder: memory: B*S (+ N)
  • For LinkedList: memory: S (re-use green!) (+ N)

2/28/2020 Compsci 201, Spring 2020 47

slide-45
SLIDE 45

linked list improvement: time

  • Suppose w

e we have B B "gat" ( (blue lue), i , in strand nd s siz ize N N

  • Inserting size S "gggtttaaa" (green) splicees
  • For String: time: B2S + N, builder: BS + N
  • For LinkedList: B + N

2/28/2020 Compsci 201, Spring 2020 48

slide-46
SLIDE 46

Theory and Practice

  • The J

JVM c can s n sometim imes es o

  • ptim

imize e your c code

  • Don’t optimize what you don’t have to …
  • http://www.pellegrino.link/2015/08/22/string-

concatenation-with-java-8.html

  • Timing

ings w with h System.nanoTime() are s suspect

  • Other things going on in computer
  • JVM can go into garbage-collection mode
  • Other considerations

2/28/2020 Compsci 201, Spring 2020 49

slide-47
SLIDE 47

Thoughts on Exam 1

  • Exa

Exam 1 – 80 80 point ints

2/28/2020 Compsci 201, Spring 2020 50

slide-48
SLIDE 48

Survey on Exam 1

2/28/2020 Compsci 201, Spring 2020 51

slide-49
SLIDE 49

Big-Oh Questions

  • Need

eed t to ex explain every line line

  • We

We will ill do do bi big-Oh Oh a almos

  • st eve

very day

  • The

The more re yo you do do the he better y you u will g ill get a at t the hese

2/28/2020 Compsci 201, Spring 2020 56

slide-50
SLIDE 50

Storage Question

  • Class h

has s state – four i item ems d def efine a ine an object ct

  • Int mySize
  • Int myCapacity
  • String[] myItems
  • HashSet<String> myUniqueItems
  • Met

etho hods s should ld upda pdate sta tate appr ppropr priately

  • Lo

Lot of

  • f point

ints, b but ut b broken int into s small l par arts

2/28/2020 Compsci 201, Spring 2020 57

slide-51
SLIDE 51

Exam 1 Takeaways

  • First, u

, under erstand nd e ever erything hing you missed

  • Get a blank sheet of paper, can you now write

the code.

  • Need to do this before moving on
  • Exa

Exam and and solut lutio ions ns are re on

  • n the

he Old Te Tests pag age

  • Com
  • me in

in fo for offic ice ho hour urs – go go ov

  • ver yo

your ex exam am, concepts ts yo you are re not

  • t solid

id on

  • n
  • Go on nights when an assignment/APT not due
  • Free four hours a night office hours

2/28/2020 Compsci 201, Spring 2020 58

slide-52
SLIDE 52

More Exam 1 Takeaways

  • Midterm g

grad ades es – most w will p ill pull ull up up your ur grad ade w wit ith h

  • the

her t thin hings

  • A range – 119
  • B range – 135
  • C range – 30
  • Help

elp

  • Understand what you missed
  • Consulting/Office hours – it is free!
  • Peer Tutoring Center – group tutoring

2/28/2020 Compsci 201, Spring 2020 59