Compsc sci 201 201 Wo Work, Nbody dy, , ArrayL yLists ts - - PowerPoint PPT Presentation

compsc sci 201 201 wo work nbody dy arrayl ylists ts
SMART_READER_LITE
LIVE PREVIEW

Compsc sci 201 201 Wo Work, Nbody dy, , ArrayL yLists ts - - PowerPoint PPT Presentation

Compsc sci 201 201 Wo Work, Nbody dy, , ArrayL yLists ts Susan Rodger January 29, 2020 1/29/2020 Compsci 201, Spring 2020 1 F is for Folder aka Directory where things are stored in Git Function Abstraction a


slide-1
SLIDE 1

Compsc sci 201 201 Wo Work, Nbody dy, , ArrayL yLists ts

1/29/2020 Compsci 201, Spring 2020 1

Susan Rodger January 29, 2020

slide-2
SLIDE 2

F is for …

  • Folder
  • aka Directory – where things are stored in Git
  • Function
  • Abstraction – a method in Java

1/29/2020 Compsci 201, Spring 2020 2

slide-3
SLIDE 3

PFTW

  • Get

etting ng t thing ngs done i ne in 201

  • How to succeed and enjoy the effort
  • Mund

ndan ane J e Java-is isms ms

  • From char to autoboxing: primitives
  • What is this?
  • Gener

neric classes es: H How Ar ArrayList st wo works

  • Design, create, test, measure

1/29/2020 Compsci 201, Spring 2020 3

slide-4
SLIDE 4

Getting Things Done in 201

  • What do these d

dat ata m mean f n for y you, u, f for m me, f for t the communit unity o

  • f 286 s

stud udent ents i in Compsc sci 201? 201?

1/29/2020 Compsci 201, Spring 2020 7

slide-5
SLIDE 5

From Last Time … Go over WOTO: Correctness Counts

http://b ://bit.l .ly/20 /201s 1spring2 g20-012 124-2

1/24/2020 Compsci 201, Spring 2020 8

slide-6
SLIDE 6

Object class, equals method

  • In

In Java vaDoc

  • Signa

natur ure o e of equals als met etho hod

1/29/2020 Compsci 201, Spring 2020 9

slide-7
SLIDE 7

@Override .equals

  • Create a new P

Point m met etho hod

  • Use annotation @Override, help with errors

boolean equals(Object o) { …

  • Must u

use t e this is s signa natur ure, t to implem lement ent:

  • Cast parameter appropriately
  • Compare instance fields

1/29/2020 Compsci 201, Spring 2020 10

slide-8
SLIDE 8

Point inherits Object.equals

  • This d

s doesn sn’t w t work f k for Point o t objects ts!

  • Def

efault ult simply uses ==, no idea about points

  • a.equals(b) if a and b ref

eference nce t the same o e object ect

  • Two different (0,0) points not the same

1/29/2020 Compsci 201, Spring 2020 11

slide-9
SLIDE 9

Point equals fixed!

  • Must u

use s e same s e signa natur ure

  • Must c

st cast st O Object to t to Point

1/29/2020 Compsci 201, Spring 2020 12

slide-10
SLIDE 10

Contract for Equality

1/29/2020 Compsci 201, Spring 2020 16

  • Reflex

lexiv ive e x.equals(y) then y.equals(x)

  • Trans

ansit itivit ivity: : x.eq(y), y.eq(z) then n x.eq(z)

  • Check x.equals(x) as

as a a special c ecial cas ase w e with = h ==

  • Check this.getClass() == o.getClass()
  • Don’t want to have an apple == orange
  • Cas

ast O Object ct p param ameter er a and u use i e instance ance va variab iables les

  • See Point as example
slide-11
SLIDE 11

Amanda Randles, Duke 2005

  • ACM Grace M

Murray H Hoppe pper Aw Award ( d (<= 35 yo yo)

1/29/2020 Compsci 201, Spring 2020 17

For developing HARVEY, a massively parallel circulatory simulation code capable of modeling the full human arterial system at subcellular resolution and fostering discoveries that will serve as a basis for improving the diagnosis, prevention, and treatment of human diseases. //XXX and Amanda Peters //Compsci 100: Huffman Coding //November 19, 2002 I felt like working in a pair was a really successful way to complete the program. It helped the most when it came to working out basic logic and finding errors. I found it really helpful because he often would see the basic logic to the code and I could help more with the implementation. I feel like it was a successful group and we both contributed a lot.

slide-12
SLIDE 12

Reading Points

  • We'll t

ll typic ically lly u use a e a Scanne nner t to read value ues

  • Use .hasNext(),.hasNextDouble(), …
  • If/while there's more to read? Call .next()
  • Met

etho hod .next() retur urns ns a a String ing

  • Method .nextDouble() returns a double …
  • See

e PointRea eader er.j .java cla lass, us useful in in NB NBod

  • dy

1/29/2020 Compsci 201, Spring 2020 18

slide-13
SLIDE 13

Scanner Sources for Reading

  • Construct

uct a a Scanne anner f from System em.in .in

  • Reads from keyboard/console
  • .hasNextX()true until end-of-file OR no X
  • Control-D on OS X, Control-Z on Windows
  • Cons

nstruct a a Scanner f from a a File ile

  • Reads from file, ex

exception c could uld hap happen

  • .hasNextX()true until all of file read OR no X
  • Each call of .nextX() returns the next X, internally

the Scanner "remembers" where it last read

1/29/2020 Compsci 201, Spring 2020 19

slide-14
SLIDE 14

Scanner hasNext and next

  • Think

nk a about ut s scanner nner a as a a long r reel/s l/sour urce ce of data

  • If .hasNext() returns true, there is

something to read by Scanner cursor/reader

  • Calling .next() returns and

and ad advances cursor

  • Scanner object maintains cursor internally
  • Source: f

: file, S , String ing, , terminal inal, … , …

1/29/2020 Compsci 201, Spring 2020 20

slide-15
SLIDE 15

N-Body Simulation

  • Class Celes

lestialB ialBody repres esent ents C Celes lestia ial B l Body

  • Planet, Sun, Asteroid
  • Models an object in 2D space, not 3D
  • Position, Velocity, Mass, Image for display
  • Class NB

NBod

  • dy drives

es t the s simula ulation

  • Compute gravitational forces: physics
  • Time-step simulation
  • compute all forces, update ,display

1/29/2020 Compsci 201, Spring 2020 21

slide-16
SLIDE 16

Class CelestialBody

  • Illus

lustrates s stand andard J Java i idioms

  • Constructors, Methods, Instance Variables
  • State i

is private: s : six i instanc nce v e variab iable les

  • myXPos, … using my

my convention - this object

  • Initialized by constructors
  • Methods ar

are p e pub ubli lic

  • Include access

ssors aka getters for state

  • No setters, cannot change myXPos other than

via the update method, a mutator

1/29/2020 Compsci 201, Spring 2020 22

slide-17
SLIDE 17

The Object Concept

  • Every i

instan ance ce v variab able a and ever ery non-sta tatic tic m meth thod d acces cessed ed/cal called ed a after Obj bject. t.Dot

  • b.getX(), b.calcForcExertedBy(other)
  • From w

withi hin a n a class, e e.g., Celestia tialB lBody

  • myXPos, getX(),this.myXPos,
  • All are equivalent as is this.getX()
  • Some

e prefer er a always using t

  • this. – clear

earer er?

1/29/2020 Compsci 201, Spring 2020 23

slide-18
SLIDE 18

NBody numbers

  • Floating

ing p point nt i issue ues, p , proble lems, q , quand ndaries ies

  • When is (a + b) + c != a + (b + c)
  • When is a/b * c != a*c / b
  • Watch for this in Gradescope tests!!

1/29/2020 Compsci 201, Spring 2020 25

slide-19
SLIDE 19

Debugging Arithmetic

  • Order

er o

  • f operatio

ions ns w with f h floating ing p point v values ues c can n result ult i in overflo low, u , under erflo low, m , more

  • Small number + Big number …

1/29/2020 Compsci 201, Spring 2020 26

slide-20
SLIDE 20

Debugging double Arithmetic

  • Integer v

values ues a are n not the s same as e as D Double v le values ues

  • 1/0 is … whereas 1.0/0 is …

1/29/2020 Compsci 201, Spring 2020 27

slide-21
SLIDE 21

Completing NBody

  • Please r

e read t the e TL;DR d docum cument nt

  • Test at each step, push constantly using Git
  • Afte

ter usin ing suppli pplied T d Test… c classes, p proceed d to to simu mula lati tion

  • Must be able to read data file to simulate
  • Understand the basics, read carefully
  • Analysis

is: comple mplete b before s submit mittin ting to to Gradesc scop

  • pe

for final s submissi ssion

  • n

1/29/2020 Compsci 201, Spring 2020 28

slide-22
SLIDE 22

Now look at DNAMaxNucleotide

  • Retur

urn n the s strand and f from s strand ands a array w with m h most

  • ccur

urrence nces o

  • f nucleo

cleotid ide e nuc

  • nuc. R

. Retur urn l n longes est such s ch strand nd

  • Exa

Exampl ple

1/29/2020 Compsci 201, Spring 2020 29

slide-23
SLIDE 23

Algorithm - DNAMaxNucleotide

  • Does

es t thi his co code m e mak ake t the he alg algorithm c cle lear?

  • Why must count be a helper method?
  • Why can't max = 0 before loop?

1/29/2020 Compsci 201, Spring 2020 30

slide-24
SLIDE 24

Two Versions of Helper Method

  • Iter

erating ing o

  • ver each c

ch char aract acter er o

  • f a string

ng

  • Note that nuc is a one-character string
  • How does s.substring(a,b) work?

1/29/2020 Compsci 201, Spring 2020 31

slide-25
SLIDE 25

Critique of another implementation

  • Where d

e does t this is s solut lutio ion c n come from?

  • Strings are immutable, s.replace(…)
  • Replace every "a" with "" (nothing)
  • Is this better? Different? More clever? More of a

hack? …

1/29/2020 Compsci 201, Spring 2020 32

slide-26
SLIDE 26

WOTO

http:// //bi bit.ly/2 /201spr pring20-01 0129 29-1

1/29/2020 Compsci 201, Spring 2020 33

slide-27
SLIDE 27

Donald Knuth

  • aka “The Donald”
  • Turing award (and others)
  • Author of “The Art of

Computer Programming”

  • Arguably most important book

written in Computer Science

  • First publication: Mad Magazine

1/29/2020 Compsci 201, Spring 2020 34

If you optimize everything you will always be unhappy. Everyday life is like programming, I guess. If you love something you can put beauty into it.

https://www.youtube.com/watch?v=cK7yyjXfbc4

slide-28
SLIDE 28

From Array to ArrayList

  • Have int[], String[], CelestialBody[]
  • Array of any type, but d

doesn sn't g 't grow

  • Can't use .contains with array, can't print
  • The

The java.ut utils ils.Arrays cla lass ha has s some hel help

1/29/2020 Compsci 201, Spring 2020 35

slide-29
SLIDE 29

java.util.ArrayList

  • Growab

able a le array w with m h many u useful m ul met etho hods

  • https://docs.oracle

le.com/en en/java/javase/ e/11 11/docs/ap api/ i/java. a.base/ e/java/ a/util/ il/Lis ist.html

  • Can only contain Object types (no primitives)
  • Convert f

fro rom a m arra ray?

  • Arrays.asList
  • It's a List!
  • String yes, int no

1/29/2020 Compsci 201, Spring 2020 36

slide-30
SLIDE 30

From Array to ArrayList

  • Can m

n make c e conv nver ersio ion w n with O Object ect, e e.g., ., S String ing

  • Use Arrays.asList as a bridge, be careful

1/29/2020 Compsci 201, Spring 2020 37

slide-31
SLIDE 31

Primitive Array? do it yourself

  • No bridge

ge f fro rom m Arrays.asL sList st since p nce primit itiv ive

  • Loop and use autoboxing/unboxing
  • Conversion of int to Integer and vice versa

1/29/2020 Compsci 201, Spring 2020 38

slide-32
SLIDE 32

Objects, Primitives, Arrays/Lists

  • ar

array c can ho an hold ld any any type: int[], String[]

  • ArrayList only

ly O Object ct t types es, n not p primit itiv ives

  • Autoboxing allows for add/get int ::: Integer
  • ArrayList<Object> a,

a, a.toArray(…) array ay

  • Syntax is not intuitive, see examples in code
  • Arrays.asList(Object[]) to

to ArrayList

  • Actually returns List, not ArrayList, …

1/29/2020 Compsci 201, Spring 2020 39

slide-33
SLIDE 33
  • - real world APT?
  • https://l

://lee eetcod

  • de.com/p

/prob

  • blem

ems/u /unique-mo morse-cod

  • de-word

rds/

  • "a" > ".-", "b" > "-..."
  • "z" > "--.."
  • Note "gin" > "--...-." and "zen" > "--...-."
  • Giv

iven an ar an array o

  • f strings, ho

how many any uniq unique enc encodin ings ar are t e ther here?

  • Also given String[] of 26 Morse codes, where

code[0] = ".-" for "a"

1/29/2020 Compsci 201, Spring 2020 40

slide-34
SLIDE 34

High Level Ideas

  • Fir

irst s step: w wha hat alg algorithm/method w will y ill you u us use?

  • Verify that it's correct. High level isn't easy
  • Is it n

nece cessary t to look a at/p /proce cess e ever ery string ing?

  • What value i

ue is retur urne ned, h , how to det eter ermine v ine value ue?

  • Stop, t

, think nk, d don't c code, … …

1/29/2020 Compsci 201, Spring 2020 41

slide-35
SLIDE 35

Solution

  • What'

t's a s a hig high le level solut lutio ion n using ng k known t n tools ls?

  • What is the method makeMorse() ?
  • Talk to your interviewer … it's a dialog

1/29/2020 Compsci 201, Spring 2020 42

slide-36
SLIDE 36

From Nothing to Done

  • Basic id

idea eas: ho how do we e acc access enc encodings in in an an ar array wher here c code[ e[1] is is for ' 'b', " "-…" …"

  • Arithmetic with char values, 'b' – 'a' == 1
  • What about (int) 'b' == 97?
  • https://youtu.be/xLpfbcXTeo8?t=49
  • Loop over c

r chara racters rs i in a Stri ring? g?

  • Index k with s.charAt(k)
  • Or for(char ch : s.toCharArray()){

1/29/2020 Compsci 201, Spring 2020 43

slide-37
SLIDE 37

WOTO with Live/Leet Code

  • Id

Ideas f for

  • r s

sol

  • lving Le

LeetCode problem lem

  • Given array of Strings, return number of unique

Morse code encodings

  • How is a set useful here? Doable without?

1/29/2020 Compsci 201, Spring 2020 44

slide-38
SLIDE 38

From DNAMax to Morse Code

  • loop
  • op on
  • n 1

18-23, wh why do does ch ch-'a' a' serve as e as i index ex?

  • Primitive char is an int except when printed

1/29/2020 Compsci 201, Spring 2020 45

slide-39
SLIDE 39

ArrayList<…>

  • Gener

eric a ic aka p a param ameter erized ed t type

  • Any Object subtype can be in ArrayList<..>
  • Integer, D

, Double, C Char, B , Boolean an are wrapper er classe sses f s for p primiti tives

  • Mostly these work. But immutable. Cannot

increment an Integer, can create new one

1/29/2020 Compsci 201, Spring 2020 46

slide-40
SLIDE 40

WOTO

http:// //bi bit.ly/2 /201spr pring20-01 0129 29-2

1/29/2020 Compsci 201, Spring 2020 50