Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall...

101
Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China – Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October 6th, 2019

Transcript of Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall...

Page 1: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Introduction to Computer ScienceCSCI109

AndrewGoodneyFall2019

China– Tianhe-2

ReadingsSt.Amant,1-4,8

Lecture6:FirstHalfReview October6th,2019

Page 2: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Where are we?

1

Page 3: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Review

u Lasttimewegotalittleahead

u Sowe’llreviewthefirsthalfofthesemester

2

Page 4: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #1

3

Page 5: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #1

4

Page 6: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Computational Thinking

u “thoughtprocessesinvolvedinformulatingproblemsandtheirsolutionssothatthesolutionsarerepresentedinaformthatcanbeeffectivelycarriedoutbyaninformation-processingagent” (Cuny,Snyder,Wing)

v wayofsolvingproblems,designingsystems,andunderstandinghumanbehaviorthatdrawsonconceptsfundamentaltocomputerscienceu Toflourishintoday'sworld,computationalthinkinghastobeafundamentalpart

ofthewaypeoplethinkandunderstandtheworldv creatingandmakinguseofdifferentlevelsofabstraction,tounderstandand

solveproblemsmoreeffectivelyv thinkingalgorithmically andwiththeabilitytoapplymathematicalconcepts

suchasinduction todevelopmoreefficient,fair,andsecuresolutionsv understandingtheconsequencesofscale,notonlyforreasonsofefficiency

butalsoforeconomicandsocialreasons

5

Humansthinking(i.e.,transforminginformation)todeviseproceduresforexecutionbyinformationtransformers(humanand/ormachine)

Page 7: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Before Mechanical Computers

Electroniccomputerswereprecededbymechanicalcomputersandmechanicalcomputerswereprecededby…

…looms

6

Page 8: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Discrete Machines: State

uHowdoestheloombehaveasafunctionoftime?u Atanygiventimeasetofthreadsisraisedandtherestarelowered

uWritingdownthesequenceofraised(andlowered)threadstellsusthestepsthemachinewentthroughtoproducethecloth/tapestry/whatever

u Thepatternofraised(andlowered)threadsiscalledthestate ofthemachine

7

Page 9: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

CS Topic: State

u StateisaverycommonCSconcept

u Herewehavethestateofaphysicalmachine

u InCSwetalkaboutthe“state”ofanobjectv Ofadatabasev Ofarobotv Ofa“state-machine”(finite,Turing,etc…)v Ofasystem(physicalorvirtual)v …

u Thenweneedawaytodescribethestatev Givesusthenotionofanencoding

8

Page 10: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

CS Topic: Discrete Machines, State and Encoding

u Choosingastaterepresentationtakesskill.Thestateshouldbev Parsimonious:itshouldbea“small”descriptorofwhatthemachineis

doingatanygiventimev Adequate:itshouldbe“bigenough”tocaptureeverything“interesting”

aboutthemachine

u Thesearesometimescontradictory.Theyarealsoqualitativeanddependonwhatbehaviorofthemachinewewanttodescribe

uUsuallyyouneedavocabulary(encoding)todescribestate.Inthecaseofaloom,statecanbeexpressedasabinarypattern(1forraised,0forlowered)

9

Page 11: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Discrete Machines: Abstraction

u Theloomisadiscretemachinev Stateisbinarypattern– i.e.discretev Thenotionoftimeisdiscrete– i.e.timeismodeledasproceedinginstepsor

finitechunks

uMoreprecisely,theloomcanbeusefullymodeledasadiscretemachinev Becauseofcoursebeingaphysicaldevicethereisvariation,nothingis

exactlyprecisev Butmodelingthemachineasdiscreetisgoodenoughandworksforthis

purpose

u Thisisanexampleofanabstraction – akeyconceptinComputerScience 10

Page 12: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

CS topic: Abstraction

u Oneofthefundamental“things”wedoinCS

u Reducingordistillingaproblemorconcepttotheessentialqualitiesv Simplesetofcharacteristicsthataremostrelevanttotheproblem

u Many(most,all)ofwhatwedoinengineeringandcomputerscienceinvolvesabstractions

u Heretheabstractionismodellingtheloomasasimplediscreetstatemachinev Makesitpossibletounderstandv Andmakesitpossibleto“program”theloom

11

Page 13: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #1

u Whatmakesacomputer?v Lotsofthingscanhelpuscompute(informationtransformation)v Computersneed

u Memoryu Control-flow

u State

u Abstraction

12

Page 14: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #2

13

Page 15: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Motivation

u Whatdocomputersdo?v Mathwithbinarynumbers

u Sowhatdoweneedtobuildacomputer?v Placetostorebinarynumbersv Waytodomath

14

Page 16: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Arithmetic/Logic

u “math”weneedtodowithnumbersinmemoryv ADDv SUBTRACTv MULTIPLYv DIVIDEv AND,OR,XOR,NOTv Etc…

u Assumewecanbuildacircuitthatcandothisu Takesnumbersrepresentedasdigital(electrical)values,producesresultsasthesame

15

OP2

Page 17: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Start building a circuit…

16

bus

Page 18: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Instructing the CPU

u Nowwecanmakeinstructions…

u Instructionsarebinarynumbersthattellthecircuitwhattodo

u Selectthe1st operand,2nd operand,destinationandfunction

u Withaseriesofsuchinstructionsthecircuitcanperformarbitrarycomputations

17

Page 19: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Where to get the instructions?

u InstructionMemory

18Controller

ALU

Page 20: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

How to compute?

u Fillinstructionmemorywithdesiredprogram

u Initializedatamemory

u Runaninstruction(givenbyprogramcounter)v Thenincrementprogramcounterv Runnextinstruction,incrementprogramcounter…

u Someearlycomputerswereprettymuchjustthis

19

Page 21: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

The Central Processing Unit (CPU)

20

u Controller+ALU=CentralProcessingUnit(CPU)u CPUhasasmallamountoftemporarymemorywithinit

v Registersv Aspecialregistercalledtheprogramcounter(PC)

u CPUperformsthefollowingcyclerepeatedly

FetchInstruction

DecodeInstruction

ExecuteInstruction

Page 22: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Fetch-Decode-Excecute

u Fetchv Getthenextinstructionfrommemory

u Decodev SendthepropersignalsfromthecontrollertotheALUandRegisters

u Executev LettheALUdoitsworktoproducearesult

21

Page 23: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

The Storage Hierarchy

22

Cheaper&larger

FasterRegisters

RAM(memory)

SecondaryStorage(DiskSpace)

Page 24: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Trade-offs

u Anaside…

u Identifyingtrade-offsisafundamentalengineeringskill

u Understandingandbalancingtrade-offsispartofdesignprocess

u Notalwayseasytomanage!

u Conflictinginterests

u Speedvs.spaceisverycommontradeoffinCSv Soifyouwantfasterexecutionyouneedmorememory

23

Page 25: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Cache

u Small(butbiggerthanregisters)u Volatileu Fast(notasfastasregisters,butfasterthanRAM)uWhattokeepinthecache?

v Thingsthatprogramsarelikelytoneedinthefuturev Localityprinciple:

u Lookatwhatitemsinmemoryarebeingusedu Keepitemsfromnearbylocations(spatiallocality)u Keepitemsthatwererecentlyused(temporallocality)

24

Page 26: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Modern Computer Architecture diagram

25

Controller

ALU

I/O Devices

(USB, etc)

CPU

Registers &

Program Counter

Memory

DRAM

Disk

L2

Cache

L3

Cache

Boot ROM

I/O Controller

Disk controller

On die, but not

part of "CPU"

Page 27: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Programming a CPU

u Howtocompute?

u Developaseriesoflow-levelinstructionsv Usingtheregistersand/ormainmemoryforstoragev Usingonlylow-leveloperationsmadeavailablebytheparticularCPU

u ”Assemblylanguage”v Ormaybeevenmachinecode(probablynot,though)

26

Page 28: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Typical Operationsu ADDRi Rj Rk AddcontentsofregistersRi andRj andputresultinregisterRku SUBTRACTRi Rj Rk SubtractregisterRj fromregisterRi andputresultinregisterRku ANDRi Rj Rk BitwiseANDcontentsofregistersRi,Rj andputresultinregisterRku NOTRi BitwiseNOTthecontentsofregisterRiu ORRi Rj Rk BitwiseORthecontentsofregistersRi,Rj andputresultinregisterRku SETRi value SetregisterRi togivenvalueu SHIFT-LEFTRi ShiftbitsofregisterRi leftu SHIFT-RIGHTRi ShiftbitsofregisterRi rightu MOVERi Rj CopycontentsfromregisterRi toregisterRju LOADMi Ri CopycontentsofmemorylocationMi toregisterRiu WRITERi Mi CopycontentsofregisterRi tomemorylocationMiu GOTOMi JumptoinstructionstoredinmemorylocationMiu COND_GOTORi Rj Mi IfRi >Rj,jumptoinstructionstoredinmemorylocationMi

27

Page 29: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #2 Summary

u Computersdotwothings:v BinaryMathv Movedata

u Sowebuildastatemachine(CPU):v Controller,Registers,ALUv Fetch-Decode-ExecuteCycle

u MemoryHierarchyandCaching

u AssemblyLanguageProgramming

28

Page 30: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #3

29

Page 31: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

u “Thearchitecturelevelgivesusaverydetailedviewofwhathappensonacomputer.Buttryingtounderstandeverythingacomputerdoesatthislevelwouldbe…(insertanalogyaboutperspective).Ifallwecanseeisfinedetail,itcanbehardtograspwhat’shappeningonalargerscale.”

30

Page 32: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Problem Solving

u Architectureputsthecomputerunderthemicroscopev Imaginesolving*all*problemsbythinkingaboutthecomputeratthe

architecturelevel

u Earlycomputerscientists*had*todothisv Luckilywedon’t.

31

Page 33: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Problem Solving

u Computersareusedtosolveproblemsu Abstractionforproblems

v Howtorepresentaproblem?v Howtobreakdownaproblemintosmallerparts?v Whatdoesasolutionlooklike?

u Twokeybuildingblocksv Abstractdatatypesv Algorithms

32

Page 34: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Abstract Data Types

uModelsofcollectionsofinformationv Chosentohelpsolveaproblem

u Typicallyatanabstractlevelv Don’tdealwithimplementationdetails:memorylayout,pointers,etc.

“…describeswhatcanbedonewithacollectionofinformation,withoutgoingdowntothelevelofcomputerstorage.”[St.Amant,pp.53]

33

Page 35: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Motivation for Abstract Data Structures

u Thenatureofsomedata,andthewayweneedtoaccessesitoftenrequiressomestructure,ororganizationtomakethingsefficient(orevenpossible)

u Data:largesetofnames(maybeattendancedata)

u Problems:didJelenaattendon9/9?HowmanylecturesdidMarioattend?Whichstudentsdidn’tattend8/26?

34

Page 36: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sequences, Trees and Graphs

35

u Sequence:alistv Itemsarecalledelementsv Itemnumberiscalledtheindex

uGraph

u TreeEric

Emily Jane

Terry Bob

Jim

Mike Chris

Bob

Page 37: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sequences aka Lists

u Sequencesareourfirstfundamentaldatastructure

u Sequencesholditemsv Items=whateverweneed.It’sabstract.

u Sequenceshavethenotionoforderv Itemscomeoneafteranother

u Sequencescanbeaccessedbyindex,orrelativev Findthe5th itemv Ormovetonextorpreviousfromcurrentitem

u The“how”(implementation)isnotimportant(now)v Arrays(C,C++),Vectors(C++),ArrayList (Java),Lists(Python)…v Thesearealldifferentimplementationsofthisabstractdatastructure

36

Page 38: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sequence Tasks

u Most“questions”(problems)thataresolvedusingsequencesareessentiallyoneoftwoquestions:

u IsitemAinsequenceX?

u WhereinsequenceYisitemB?

u Bothoftheseareansweredbysearchingthesequence

37

Page 39: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sequences: Searching

u Sequentialsearch:startat1,proceedtonextlocation…

u Ifnamesinthelistaresorted (sayinalphabeticalorder),thenhowtoproceed?v Startinthe‘middle’v Decideifthenameyou’relookingforisinthefirsthalforsecondv ‘Zoomin’tothecorrecthalfv Startinthe‘middle’v Decideifthenameyou’relookingforisinthefirsthalforsecondv ‘Zoomin’tothecorrecthalfv …

u Whichismoreefficient(underwhatconditions)?38

bruteforce

divide-and-conquer

Page 40: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sorting

u Ifsearchingasortedsequenceismoreefficient(persearch),thisimpliesweneedawaytosortasequence!

u SortingalgorithmsarefundamentaltoCSv UsedALOTtoteachvariousCSandprogrammingconcepts

u ComputerScientistslikecomingupwithbettermoreefficientwaystosortdatav Evenhavecontests!

u We’lllookattwoalgorithmswithverydifferentdesignsv SelectionSortv QuickSort

39

Page 41: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sorting: Selection Sort

40

u Sorting:puttingasetofitemsinorderu Simplestway:selectionsort

v Marchdowntheliststartingatthebeginningandfindthesmallestnumber

v Exchangethesmallestnumberwiththenumberatlocation1v Marchdowntheliststartingatthesecondlocationandfindthesmallestnumber(overallsecond-smallestnumber)

v Exchangethesmallestnumberwiththenumberatlocation2v …

Page 42: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sorting: Quicksort

41

u Picka‘middle’elementinthesequence(thisiscalledthepivot)

u Putallelementssmallerthanthepivotonitsleft

u Putallelementslargerthanthepivotontheright

u Nowyouhavetwosmaller sortingproblemsbecauseyouhaveanunsortedlisttotheleftofthepivotandanunsortedlisttotherightofthepivot

u Sortthesequenceontheleft(useQuicksort!)v Picka‘middle’elementinthesequence(thisiscalledthepivot)

v Putallelementssmallerthanthepivotonitsleft

v Putallelementslargerthanthepivotontheright

v Nowyouhavetwosmaller sortingproblemsbecauseyouhaveanunsortedlisttotheleftofthepivotandanunsortedlisttotherightofthepivot

v Sortthesequenceontheleft(useQuicksort!)

v Sortthesequenceontheright(useQuicksort!)

u Sortthesequenceontheright(useQuicksort!)v Picka‘middle’elementinthesequence(thisiscalledthepivot)

v Putallelementssmallerthanthepivotonitsleft

v Putallelementslargerthanthepivotontheright

v Nowyouhavetwosmaller sortingproblemsbecauseyouhaveanunsortedlisttotheleftofthepivotandanunsortedlisttotherightofthepivot

v Sortthesequenceontheleft(useQuicksort!)

v Sortthesequenceontheright(useQuicksort!)

Page 43: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Quicksort

42

Page 44: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #3 Summary

u Solvingaproblemwithacomputerusuallyinvolves:v Astructuredwaytostore(organize)datav Analgorithmthataccessesandmodifiesthatdata

u Algorithmshavecharacteristics,likebrute-force ordivide-and-conquer thathelpusunderstandhowtheywork

u Thinkingaboutabstractdatatypesandalgorithmsfreesusfromworryingabouttheimplementationdetails

u SequencesareafundamentalADTusedtoorganizedatainanorderedlist.u Sequencescanbesearched:

v Linearsearch(brute-force)v Binarysearch(divide-and-conquer),butrequiressortedlist

u Sequencescanbesorted:v Selectionsort(brute-force)v Quick-sort(divide-and-conquer

43

Page 45: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #4

44

Page 46: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Abstract Data Types

uModelsofcollectionsofinformationu Typicallyatanabstractlevel

“…describeswhatcanbedonewithacollectionofinformation,withoutgoingdowntothelevelofcomputerstorage.”[St.Amant,pp.53]

45

Page 47: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Sequences, Trees and Graphs

46

u Sequence:alistv Itemsarecalledelementsv Itemnumberiscalledtheindex

uGraph

u TreeEric

Emily Jane

Terry Bob

Jim

Mike Chris

Bob

Page 48: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Motivation for Abstract Data Structures (Graphs, Trees)

u Thenatureofsomedata,andthewayweneedtoaccessesitoftenrequiressomestructure,ororganizationtomakethingsefficient(orevenpossible)

u Data:largesetofpeopleandtheirfamilyrelationshipusedforgeneticresearch

u Problems:twopeopleshareararegenetictrait,howcloselyaretherelated?(motivatesforatree)

47

Page 49: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Motivation for Abstract Data Structures (Graphs, Trees)

u Dataset:roadsandintersections.

u Problem:howtotravelfromAtoB@5pmonaFriday?Howtoavoidtrafficvs.preferfreeways?(motivatesaweightedgraph)

u Dataset:freightenterscountryatbigport(LA/LongBeach).

u Problem:Howtoroutefreightgiventrainlines/connections?v Routefastest,vs.lowestcost?

u Dataset:airportlocations

u Problem:howtorouteanddeliverapackagetoanyaddressintheUSwithminimumcost?ThinkUPS,FedEx

48

Page 50: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Motivation for Abstract Data Structures (Graphs, Trees)

u Dataset:networkswitchesandtheirconnectivity(networklinks)

u Problem:Choseasubsetofnetworklinksthatconnectallswitcheswithoutloops(networksdon’tlikeloops).Motivatesgraphs,andgraph->treealgorithm

49

Page 51: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Motivation for Abstract Data Structures (Graphs, Trees)

u Dataset:potentialsolutionstoabigproblem

u Problem:howtofindanoptimalsolutiontotheproblem,withoutsearchingeverypossibility(solutionspacetoobig).Motivatesgraphsandgraphsearchtosolveproblems.

u Otherdata/problemsthatmotivategraphs/trees:v Financialnetworksandmoneyflows,socialnetworks,renderingHTML

code,compilers,3Dgraphicsandgameengines… andmore

50

Page 52: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Trees

u Eachnode/vertexhasexactlyoneparentnode/vertex

u Noloopsu Directed(links/edgespointinaparticulardirection)

u Undirected(links/edgesdon’thaveadirection)

u Weighted(links/edgeshaveweights)

u Unweighted (links/edgesdon’thaveweights)

51

Eric

Emily Jane

Terry Bob

Page 53: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Which of these are NOT trees?

52

1

2

3

5

6

7

4 8

Page 54: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Graph/Tree Traversal

u Traversingagraphoratree:“moving”andexaminingthenodestoenumeratethenodesorlookforsolutions

u Example:findalllivingdescendantsofXinourgeneticdatabase.

u Fortraversingagraphwepickastartingnode,thentwomethodsareobvious:v Depthfirst

u Goasdeep(farawayfromstartingnode)aspossiblebeforebacktracking

v Breadthfirstu Examineonelayeratatime

53

Page 55: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Tree Traversal

u DepthfirsttraversalEric,Emily,Terry,Bob,Drew,Pam,Kim,Jane

u BreadthfirsttraversalEric,Emily,Jane,Terry,Bob,Drew,Pam,KimEric,Jane,Emily,Bob,Terry,Pam,Drew,Kim

54

Eric

Emily Jane

Terry Bob

Drew Pam

Kim

Page 56: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Tree Traversal

u Depthfirstvs.Breadthfirsteventuallyvisitallnodes,butdosoinadifferentorder

u Usedtoanswerdifferentquestionsv Depthfirst:goodforgametrees,evaluatingdownacertainpathv Breadthfirst:lookforshortestpathbetweentwonodes(e.g for

computernetworks)

u Roughly:v Depthfirst:find‘a’solutiontotheproblemv Breadthfirst:find‘the’solutiontotheproblem

55

Page 57: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Graphs: Directed and Undirected

56

Tia

Jim

Mike

Chris

Bob

Joe

Sofie

Undirected

Tia

Jim

Mike

Chris

Bob

Joe

Sofie

Directed

Page 58: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Graph to Tree Conversion Algorithms

u Sometimesthequestionisbestansweredbyatree,butwehaveagraph

u Needtoconvertgraphtotree(bydeletingedges)

u Usuallywanttocreatea“spanningtree”

57

Page 59: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Spanning Trees

u Spanningtree:Anytreethatcoversallverticesv “Cover”=“include”ingraph-speak

u Example:graphofsocialnetworkconnections.Wanttocreatea“phonetree”todisseminateinformationintheeventofanemergency

u Example:networkofswitcheswithredundantlinksandmultiplepathsbetweenswitches(thereareloopsakacyclesinthegraph).Needtochoseasetoflinksthatconnectsallswitcheswithnoloops.

58

Page 60: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Minimum Spanning trees

uSpanningtree:Anytreethatcoversallvertices,notascommonastheMST

uMinimum spanningtree(MST):Treeofminimaltotaledgecost

u Ifyouhaveagraphwithweightededges,aMSTisthetreewherethesumoftheweightsoftheedgesisminimum

uThereisatleastoneMST,couldbemorethanoneu IfyouhaveunweightededgesanyspanningtreeisaMST 59

Page 61: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

uWhycomputetheminimumspanningtree?v Minimizethecostofconnectionsbetweencities(logistics/shipping)

v Minimizeofcostofwiresinalayout(printedcircuit,integratedcircuitdesign)

60

Page 62: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Computing the MST

uTwogreedyalgorithmstocomputetheMSTv Prim’salgorithm:Startwithanynodeandgreedilygrowthetreefromthere

v Kruskal’salgorithm:Orderedgesinascendingorderofcost.Addnextedgetothetreewithoutcreatingacycle.

u ‘Greedy’meanssolutionisrefinedateachstepusingthemostobviousnextstep,withthehopethateventualsolutionisgloballyoptimal

61

Page 63: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Prim’s algorithm

u Initializetheminimumspanningtreewithavertexchosenatrandom.

u Findalltheedgesthatconnectthetreetonewvertices(i.euncovered,ordisconnected),findtheminimumandaddittothetree

u Keeprepeatingstep2untilallverticesareaddedtotheMST

(adaptedfrom:https://www.programiz.com/dsa )

62

Page 64: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Kruskal’s algorithm

u Sortalltheedgesfromlowweighttohigh

u Taketheedgewiththelowestweight,ifaddingtheedgewouldcreateacycle,thenrejectthisedgeandselecttheedgewiththenextlowestweight

u Keepaddingedgesuntilwereachallvertices.

(adaptedfrom:https://www.programiz.com/dsa )

63

Page 65: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Shortest path

u Foragivensourcevertex(node)inthegraph,itfindsthepathwithlowestcost(i.e.theshortestpath)betweenthatvertexandeveryothervertex.

u SayyoursourcevertexisMikeu LowestcostpathfromMiketoJimisMike– Bob- Tia– Jim(cost3)

u LowestcostpathfromMiketoJoeisMike– Bob– Tia– Jim– Joe(cost4)

v Veryimportantfornetworkingapplications!

64

Tia

Jim

Mike

Chris

Bob

Joe

Sofie1 1

2

4

3

1

1

3

41

1

Page 66: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Dijkstra’s algorithm: Basic idea

u Fanoutfromtheinitialnode

u Inthebeginningthedistancestotheneighborsoftheinitialnodeareknown.Allothernodesaretentativelyinfinitedistanceaway.

u Thealgorithmimprovestheestimatestotheothernodesstepbystep.

u Asyoufanout,performtheoperationillustratedinthisexample:ifthecurrentnodeA ismarkedwithadistanceof4,andtheedgeconnectingitwithaneighborB haslength2,thenthedistancetoB (throughA)willbe4+2=6.IfBwaspreviouslymarkedwithadistancegreaterthan6thenchangeitto6.Otherwise,keepthecurrentvalue.

65

Page 67: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture 4 Summary

u TreesandGraphsv Sometimesneedtomodelinteractions,connectionsbetweendatav Vertices,edgesv Directed/undirectedv Weighted/unweighted

u GraphTraversalv BFS,DFS

u GraphtoTreev Spanningtrees,minimumspanningtrees

u Prim’s,Kruskal’s

u Shortestpath:Dijkstra’s

66

Page 68: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Lecture #5

67

Page 69: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursion

u Recursion,recursionrelations,recursivedatastructures,recursivealgorithms

u Definingadatastructureoralgorithmintermsofitself

u Manyproblemsareeasiertounderstand(implement,solve)asrecursivealgorithms

68

Page 70: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursion: abstract data types

uDefiningabstractdatatypesintermsofthemselves(e.g.,treescontaintrees)

u Soalistis:Theitematthefrontofthe

list,andthentherestofthelist(whichis,anitemandthentherestofthelist…)

69

[1,3,5,7,32,6,7,121,7…]

Page 71: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursion: abstract data types

uDefiningabstractdatatypesintermsofthemselves(e.g.,treescontaintrees)

u SoatreeisEitherasinglevertex,oravertexthatistheparent

ofoneormoretrees

70

Eric

Emily Jane

Terry Bob

Drew Pam

Kim

Page 72: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursion and algorithms

u Conceptofrecursionappliestoalgorithmsaswell

u Somealgorithmsaredefinedrecursively:v Fibonaccinumbers:

u Fib(n)=0(n=0),1(n=1),fib(n-1)+fib(n-2)

u Somecanbeexpressediteratively:v Factorial=n*(n-1)*(n-2)*(n-3)…*1

u Orrecursively:v Factorial=n*factorial(n-1)

71

Page 73: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursion and algorithms

u Ifanabstractdatatypecanbethoughtofrecursively(likealist)theseofteninspirerecursivealgorithmsaswell

u Listsum:v Sumofalist=valueoffirstitem+sumoftherestofthelist

72

Page 74: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursion: algorithms

u Definingalgorithmsintermsofthemselves(e.g.,quicksort)Checkwhetherthesequencehasjustoneelement.Ifitdoes,stopCheckwhetherthesequencehastwoelements.Ifitdoes,andtheyareintherightorder,stop.Iftheyareinthewrongorder,swapthem,stop.Chooseapivotelementandrearrangethesequencetoputlower-valuedelementsononesideofthepivot,higher-valuedelementsontheothersideQuicksorttheleftsublistQuicksorttherightsublist

73

Page 75: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursion: algorithms

uHowdoyouwriteaselectionsortrecursively?uHowdoyouwriteabreadth-firstsearchofatreerecursively?Whataboutadepth-firstsearch?

74

Page 76: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursive Selection Sort

u Howtodothis?

u Needtothinkabouttheprobleminrecursiveterms:v Thinkoftheprobleminawaythatgetssmallereachtimeyouconsider

it…v Alsoneedstohaveaterminatingcondition(basecase)

u Thinkingofselectionsortinthisway…

75

Page 77: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursive selection sort

u Selectionsortfindsminimumelement,swapstofront.Thenfindsnextsmallest,swapsto2nd… andsoon

u Observation:thefrontelementiseither:v Alreadytheminimumorv Theminimumisintherestofthelist

u Observation:oncewemovetheminimumtothefrontofthelist,wecancallselectionsortontherestofthelist

76

Page 78: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursive selection sort

u Weactuallyneedtworecursivealgorithms:v find_min(list):recursivelyfindtheindexoftheminimumitemv selection_sort(list):

u Ifthelengthofthelistisone,stop,thelistissortedu callfind_min()tofindtheminimumelement,swapwiththefrontofthelist

(ifnecessary)u Callselection_sort()ontherestofthelist

v Stopwhen”restoflist”isoneitem

77

Page 79: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Recursive DFS, BFS

u RecursiveDFSisprettyeasy:v foreachneighboruofv:

u Ifuis‘unvisited’:calldfs(u)

u RecursiveBFS…

78

Page 80: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Analysis of algorithms

uHowlongdoesanalgorithmtaketorun?timecomplexity

uHowmuchmemorydoesitneed?spacecomplexity

79

Page 81: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Estimating running time

uHowtoestimatealgorithmrunningtime?vWriteaprogramthatimplementsthealgorithm,runit,andmeasurethetimeittakes

vAnalyzethealgorithm(independentofprogramminglanguageandtypeofcomputer)andcalculateinageneralwayhowmuchworkitdoestosolveaproblemofagivensize

uWhichisbetter?Why?80

Page 82: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Analysis of binary search

u n=8,thealgorithmtakes3stepsu n=32,thealgorithmtakes5stepsu Forageneraln,thealgorithmtakeslog2nsteps 81

Page 83: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Big O notation

u Characterizefunctionsaccordingtohowfasttheygrow

u Thegrowthrateofafunctioniscalledtheorderofthefunction.(hencetheO)

u BigOnotationusuallyonlyprovidesanupperbound onthegrowthrateofthefunction

u Asymptoticgrowth

f(x)=O(g(x))asx->∞ifandonlyifthereexistsapositivenumberM suchthatf(x)≤M*g(x)forallx>x0

82

Page 84: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Conventions

uO(1)denotesafunctionthatisaconstantv f(n)=3,g(n)=100000,h(n)=4.7areallsaidtobeO(1)

u Forafunctionf(n)=n2 itwouldbeperfectlycorrecttocallitO(n2)or O(n3)(orforthatmatterO(n100))

uHoweverbyconventionwecallitbythesmallestordernamely O(n2)v Why?

83

Page 85: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

What do they have in common?

u (Binary)searchofasortedlist:O(log2n)

u Selectionsort:O(n2)

u Quicksort:O(nlogn)

u Breadthfirsttraversalofatree:O(V)

u Depthfirsttraversalofatree:O(V)

u Prim’salgorithmtofindtheMSTofagraph:O(V2)

u Kruskal’s algorithmtofindtheMSTofagraph:O(ElogE)

u Dijkstra’s algorithmtofindtheshortestpathfromanodeinagraphtoallothernodes:O(V2)

84

Page 86: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Subset sum problem

u Givenasetofintegersandanintegers,doesanynon-emptysubsetsumtos?

u {1,4,67,-1,42,5,17}ands=24 Nou {4,3,17,12,10,20}ands =19 Yes {4,3,12}

u IfasethasN elements,ithas2N subsets.u CheckingthesumofeachsubsettakesamaximumofNoperations

u Tocheckallthesubsetstakes2NNoperationsu Someclevernesscanreducethisbyabit(2Nbecomes 2N/2,butallknownalgorithmsareexponential

85

Page 87: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Travelling salesperson problem

u Givenalistofcitiesandthedistancesbetweeneachpairofcities,whatistheshortestpossibleroutethatvisitseachcityexactlyonceandreturnstotheorigincity?

u Givenagraphwhereedgesarelabeledwithdistancesbetweenvertices.Startataspecifiedvertex,visitallotherverticesexactlyonceandreturntothestartvertexinsuchawaythatsumoftheedgeweightsisminimized

u Therearen! routes(anumberontheorderofnn - muchbiggerthan2n)

u O(n!)

86

Page 88: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Enumerating permutations

u Listallpermutations(i.e.allpossibleorderings)ofnnumbers

uWhatistheorderofanalgorithmthatcandothis?

87

Page 89: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

u Sowehave:v Knapsack/Subsetsum:N*2N

v Setpermutation:n!v Travelingsalesman:n!

88

Page 90: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Analysis of problems

u Studyofalgorithmsilluminatesthestudyofclasses ofproblems

u Ifapolynomialtimealgorithmexiststosolveaproblemthentheproblemiscalledtractable

u Ifaproblemcannotbesolvedbyapolynomialtimealgorithmthenitiscalledintractable

u Thisdividesproblemsintothree groups:v Problemswithknownpolynomialtimealgorithmsv Problemsthatareproventohavenopolynomial-timealgorithmv Problemswithnoknownpolynomialtimealgorithmbutnotyetproventobeintractable

89

Page 91: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Tractable and Intractable

u Tractableproblems(P)v Sortingalistv Searchinganunorderedlistv Findingaminimumspanningtree

inagraph

90

u Intractablev Listingallpermutations(all

possibleorderings)ofnnumbers

u Mightbe(in)tractablev Subsetsum:givenasetof

numbers,isthereasubsetthataddsuptoagivennumber?

v Travellingsalesperson:ncities,n!routes,findtheshortestroute

Theseproblemshavenoknownpolynomialtimesolution

Howevernoonehasbeenabletoprovethatsuchasolutiondoesnotexist

Page 92: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Tractability and Intractability

u ‘Propertiesofproblems’(NOT ‘propertiesofalgorithms’)

u Tractable:problemcanbesolvedbyapolynomialtimealgorithm(orsomethingmoreefficient)

u Intractable:problemcannotbesolvedbyapolynomialtimealgorithm(allsolutionsareproventobemoreinefficientthanpolynomialtime)

u Unknown:notknowniftheproblemistractableorintractable(noknownpolynomialtimesolution,noproofthatapolynomialtimesolutiondoesnotexist)

91

Page 93: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Subset sum problem

u Givenasetofintegersandanintegers,doesanynon-emptysubsetsumtos?

u {1,4,67,-1,42,5,17}ands=24 Nou {4,3,17,12,10,20}ands =19 Yes {4,3,12}

u IfasethasN elements,ithas2N subsets.u CheckingthesumofeachsubsettakesamaximumofNoperations

u Tocheckallthesubsetstakes2NNoperationsu Someclevernesscanreducethisbyabit(2Nbecomes 2N/2,butallknownalgorithmsareexponential)

92

Page 94: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

P and NP

u P:setofproblemsthatcanbesolvedinpolynomialtime

u Considersubsetsumv Noknownpolynomialtimealgorithmv However,ifyougivemeasolutiontotheproblem,itiseasyformetocheckifthesolutioniscorrect– i.e.Icanwriteapolynomialtimealgorithmtocheckifagivensolutioniscorrect

uNP:setofproblemsforwhichasolutioncanbecheckedinpolynomialtime

93

Easytosolve(implieseasytocheck)

Easytocheckifsolutionisgood

Page 95: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Easy to Solve vs. Easy to Check

u Easytosolve:sortingv Solve:sortthelistinO(nlogn)v Check:isthelistsorted?O(n)v ClearlysortingisinP

u Hardtosolve:sub-setsumv Solve:generateallsubsets:O(2n)v Check:sum-upsubset.O(n)

u Hardtosolve:integerfactorizationv Solve:checkallnumbersbetween2andsqrt(n)O(2w)v Check:isonenumberafactorofanother?DivideandcheckO(n2)

94

Page 96: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

P=NP?

95

uAllproblemsinP arealsoinNPuArethereanyproblemsinNP thatarenotalsoinP?

uInotherwords,is

P =NP ?uCentralopenquestioninComputerScience

Page 97: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

P vs. NP Example

u Publickeyencryptionusestwolargeprimenumbersp,qu Ifk=p*q, thenwecansendk intheclearneed pandq todecrypt

u WhyisthisPvs.NP?v p*q clearlyPalgorithmv Findingpandq givenjustk isO(2w)wherew=sizeofthenumber

(digitsorbits)

u IfP=NPthenpublickeyencryptionwouldbe“broken”u Sidenote:ascomputershavegottenfaster,keysizegoesup,makingproblemexponentiallyharderv Keysarenow>=2048bits->22048 isapreposterouslylargenumberv Check1Bkeys/second=1.7x10600 yearstocrack

96

Page 98: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Midterm Style Questions

97

1. Basedontheinformationpresentedinclassandthelectureslides,whichcomponentisnotpartofamodernCPU:A. Arithmetic/logicunitB. ProgramCounterC. CachememoryD. DiskcontrollerE. Registers

2. Whichchoiceforpivotalwaysallowsoptimalruntimeofthequicksortalgorithm?

A.MaximumelementB.MinimumelementC.AverageamongallelementsD.AveragebetweenmaximumandminimumelementsE.Noneoftheabove

3. Inordertofindthek-thsmallestelementinalistofnintegerswerunasmany

iterationsofSelectionSortasnecessaryandthenwestop.Whatisthecomplexityofthisalgorithmintermsofk,n?A. O(k*log(n))B. O(k*n*log(n))C. O(n*log(n))D. O(k*n)E. Notenoughinformationisgiventodeterminethecorrectanswer

4. WhichisTRUEaboutDFS(depthfirstsearch)vs.BFS(breadthfirstsearch)?

A.BFSonaveragehassmallerruntimethanDFSB.DFSonaveragehassmallerruntimethanBFSC.BFScannotdetectloops(i.ewouldnotworkongraphs)D.DFScannotdetectloopsE.Noneoftheaboveistrue

5. Whichisthecorrectorderingofmemoryfromfastestaccesstoslowestaccess?

A. Registers,RAM,Cache,DiskB. Disk,RAM,Cache,RegistersC. Registers,Cache,RAM,DiskD. Cache,Registers,RAM,DiskE. Disk,Cache,RAM,Registers

1. Basedontheinformationpresentedinclassandthelectureslides,whichcomponentisnotpartofamodernCPU:A. Arithmetic/logicunitB. ProgramCounterC. CachememoryD. DiskcontrollerE. Registers

2. Whichchoiceforpivotalwaysallowsoptimalruntimeofthequicksortalgorithm?

A.MaximumelementB.MinimumelementC.AverageamongallelementsD.AveragebetweenmaximumandminimumelementsE.Noneoftheabove

3. Inordertofindthek-thsmallestelementinalistofnintegerswerunasmany

iterationsofSelectionSortasnecessaryandthenwestop.Whatisthecomplexityofthisalgorithmintermsofk,n?A. O(k*log(n))B. O(k*n*log(n))C. O(n*log(n))D. O(k*n)E. Notenoughinformationisgiventodeterminethecorrectanswer

4. WhichisTRUEaboutDFS(depthfirstsearch)vs.BFS(breadthfirstsearch)?

A.BFSonaveragehassmallerruntimethanDFSB.DFSonaveragehassmallerruntimethanBFSC.BFScannotdetectloops(i.ewouldnotworkongraphs)D.DFScannotdetectloopsE.Noneoftheaboveistrue

5. Whichisthecorrectorderingofmemoryfromfastestaccesstoslowestaccess?

A. Registers,RAM,Cache,DiskB. Disk,RAM,Cache,RegistersC. Registers,Cache,RAM,DiskD. Cache,Registers,RAM,DiskE. Disk,Cache,RAM,Registers

Page 99: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Midterm Style Questions

98

6. Considertheabovegraph.WhatisthesequenceofnodesproducedbyrunningBreadthFirstSearch(BFS)startingfromv1?ForBFSonadirectedgraphonlyfollowoutgoingedges.Ifanodehasmorethanoneoutgoingedge,followtheedgetothevertexwiththelowestindexfirst(nodeindexiskforvertexVk).

A. v1 v2 v4 v5 v7 v6 v3B. v1 v2 v4 v5 v6 v7 v3C. v1 v2 v4 v3 v6 v5 v7D. v1 v2 v4 v5 v3 v6 v7E. v1 v2 v4 v5 v3 v7 v6

7. Forthesamegraphasabove,whatisthesequenceofnodesproducedbyrunningDepthFirstSearch(DFS)startingfromv1.ForDFSonadirectedgraphonlyfollowoutgoingedges.Ifanodehasmorethanoneoutgoingedge,followtheedgetothevertexwiththelowestindexfirst(nodeindexiskforvertexVk).

A. v1 v2 v4 v3 v5 v6 v7B. v1 v2 v4 v5 v3 v7 v6C. v1 v2 v4 v3 v6 v5 v7D. v1 v2 v4 v5 v7 v6 v3E.v1 v2 v4v5v3v7v6

8. WhichoftheproblemsdescribedCANNOTbesolvedoptimallywithanMST(minimumspanningtree)?

A.Buildtheshortest-lengthbridgenetworkbetweenasetofislands.

B.Eliminateloopsinacomputernetwork.C.Givenalistofcitiesandthedistancesbetweeneachpair,findtheshortestpossibleroutethatvisitseachcityandreturnstothestartingcity.

D.Eliminatemultiplepathsbetweenanytwoverticesinagraph.E.AlloftheaboveCANbesolvedoptimallywithaMST.

6

V1 V2

2

4 10 1 3

V3 V4 V5 2 2

V6 V7

5

1

8 4

9. ImaginethatitwasprovedthatP=NP.Considerthefollowingstatements:I) Wewillbeabletoverifyanycomputationalprobleminpolynomialtime.

II) Wewillbeabletosolveanycomputationalprobleminpolynomialtime.

III) WecanbuildhardwareimplementationofanondeterministicTuringmachine

IV) Allcomputationalproblemsthatcanbeverifiedinpolynomialtimewillbesolvable

inpolynomialtime

V) WewillbeabletosolveanyNPhardprobleminpolynomialtime

A. IIandVaretrueB. OnlyIIistrueC. OnlyIVistrueD. IandIVaretrueE. AllstatementsI–Varetrue

10. Whatistheroleoftheprogramcounter?A. ItisaspecialregisterintheCPUusedtostorehigh-prioritydataB. IttracksthenumberofinstructionsexecutedbythecurrentlyexecutingprogramC. Ittracksrecentlyaccessedmemorylocationstohelpimplementtheprincipleof

temporallocality

D. ItspecifiesthememorylocationfromwheretheCPUwillfetchthenextinstructionE. IttracksthenumberofrunningprogramsaskingforaccesstotheCPU

11. WhichofthefollowingisTRUEaboutbinarysearch?A. Consideringtheinputdata,binarysearchwillALWAYShaveasmallerruntimevs.sequentialsearchonthesamedata.

B. BinarysearchcanbeappliedtoanylistC. BinarysearchhasruntimecomplexityofO(2N)foranunsortedlistD. BinarysearchcanbeimplementedrecursivelyE. Noneoftheaboveistrue

12. WhichstatementisFALSE?A. EverytreeisagraphB. EverygraphhasacycleC. AtreehasnocyclesD. Everyconnected,undirected,weightedgraphhasatleastonespanningtreeE. Thenumberofverticesintheminimumspanningtreeofagraphisthesameasthenumberofverticesinthegraphitself

Page 100: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Midterm Style Questions

99

13. Whenconsideredintermsofbig-O,chosetheorderingofthefollowingfunctionsthatisinorderofincreasingasymptoticgrowthrates:A. 2n,2n-1,2n+1B. 2n-1,2n+1,2nC. 2n-1,2n,2n+1D. Allthreeofthesefunctionshavethesamebig-Ogrowthrate,soorderisnot

important.14. ThereexistsadatastructurecalledaMaxHeapthatwillreturnit’smaximumelement

(andthenremoveitfromtheheap)inO(logn).YoucanconvertanunsortedlisttoaMaxHeapinO(n).Thus,youcansortanunsortedlistusingaMaxHeap(resultinginareverseordescendingorderedsort).Whatisthetimecomplexityofthissortingalgorithm?A. O(n2log(n))B. O(n2)C. O(log(n)*log(n))D. O(nlog(n))E. O(n)

15. Whatbestdescribesthedefinitionofanalgorithm?

A. Anunambiguousandordered,stepbystepdescriptionofactionstosolveaproblemwrittentobeunderstandablebyhumans

B. sequenceofinstructionwrittentorundirectlyonacomputerC. codedlanguageusedbyprogrammerstowriteinstructionsthatacomputercan

understandtodowhattheprogrammerwantsD. Acodewhosetargetalphabetcontainsonlydigitsand/orstringsofdigitsE. Amathematicalcalculationaccordingtosomewell-knownformula

16. Youareinamazeandafriendsuggeststhatyouputyourrighthandonthewalland

followthewalluntilyoufindtheexit.This“righthandrule”representsanalgorithmforsolvingthemaze.Whichalgorithmdiscussedinclassdoestheapproachcorrespondto?A.BreadthFirstSearchB.DepthFirstSearchC.Kruskal’sAlgorithmD.BinarySearch

1. Basedontheinformationpresentedinclassandthelectureslides,whichcomponentisnotpartofamodernCPU:A. Arithmetic/logicunitB. ProgramCounterC. CachememoryD. DiskcontrollerE. Registers

2. Whichchoiceforpivotalwaysallowsoptimalruntimeofthequicksortalgorithm?

A.MaximumelementB.MinimumelementC.AverageamongallelementsD.AveragebetweenmaximumandminimumelementsE.Noneoftheabove

3. Inordertofindthek-thsmallestelementinalistofnintegerswerunasmany

iterationsofSelectionSortasnecessaryandthenwestop.Whatisthecomplexityofthisalgorithmintermsofk,n?A. O(k*log(n))B. O(k*n*log(n))C. O(n*log(n))D. O(k*n)E. Notenoughinformationisgiventodeterminethecorrectanswer

4. WhichisTRUEaboutDFS(depthfirstsearch)vs.BFS(breadthfirstsearch)?

A.BFSonaveragehassmallerruntimethanDFSB.DFSonaveragehassmallerruntimethanBFSC.BFScannotdetectloops(i.ewouldnotworkongraphs)D.DFScannotdetectloopsE.Noneoftheaboveistrue

5. Whichisthecorrectorderingofmemoryfromfastestaccesstoslowestaccess?

A. Registers,RAM,Cache,DiskB. Disk,RAM,Cache,RegistersC. Registers,Cache,RAM,DiskD. Cache,Registers,RAM,DiskE. Disk,Cache,RAM,Registers

Page 101: Introduction to Computer Science · Introduction to Computer Science CSCI 109 Andrew Goodney Fall 2019 China –Tianhe-2 Readings St. Amant, 1-4, 8 Lecture 6: First Half Review October

Midterm Style Questions

100

17. Thealgorithmfrom#16canfailonsomemazes.Themazescanbethoughtofasgraphs.Ifthegraphrepresentationofthemazehascertainproperties,thenthe“righthandrule”mightfail.Whichpropertycancausefailure?A.Weighted(somepassagesaresmaller,orsomepassagesforceyoutocrawl)B.Cyclic(thereareloopsinthemaze) C.Planar(themazecanbedrawnasagraphwherenoedgescross) D.Acyclic(therearenoloopsinthemaze)

18. WhichofthefollowingisTRUEabouttreesandgraphs?

A.AlltreesaregraphsB.EverygraphhasexactlyoneMSTC.AlltreesaredirectedgraphsD.AllgraphsaretreesE.NotallgraphshaveaMST

19. TheJacquardLoom(andsimilarmachines)areconsideredinformationtransformers,

butnotcomputers.Whichanswerbestdescribeswhy:A.Programmingthesemachinesdoesn’tscaleB.Programmingthesemachinesrequirespunch-cardsC.MachineslikethesedonothavememoryorcontrolflowD.Machineslikethesearetoooldtobeconsideredcomputers

20. Whenaninstructionisloadedfrommemory,itisdesirabletoloadthecontentsofafewsucceedingmemoryaddressesintothecache.Whyisthat?A.TheCPUisunabletoonlyloadoneinstructionatatimeB.Thosecontentsarelikelytobeusefulintheimmediatefutureaccordingtothe

spatiallocalityprincipleC.Thosecontentsarelikelytobeusefulintheimmediatefutureaccordingtothe

temporallocalityprincipleD.Thecontentsstoredaftertheinstructionarethevaluesusedinthecomputationof

theinstructionandthereforemustbeloadedwiththeinstruction.

21. Thesubset-sumproblemhastimecomplexityO(N*2N).WheredoesthefactorNcomefrom?A:ThatishowmanysubsetsasetofsizeNhas.B:O(N)isthetimecomplexityrequiredtocheckeachpossiblesubsetsum.C:Thatisthetimecomplexityofthealgorithmthatgeneratesthesubsets.D:Noneoftheabove.

17. Thealgorithmfrom#16canfailonsomemazes.Themazescanbethoughtofasgraphs.Ifthegraphrepresentationofthemazehascertainproperties,thenthe“righthandrule”mightfail.Whichpropertycancausefailure?A.Weighted(somepassagesaresmaller,orsomepassagesforceyoutocrawl)B.Cyclic(thereareloopsinthemaze) C.Planar(themazecanbedrawnasagraphwherenoedgescross) D.Acyclic(therearenoloopsinthemaze)

18. WhichofthefollowingisTRUEabouttreesandgraphs?

A.AlltreesaregraphsB.EverygraphhasexactlyoneMSTC.AlltreesaredirectedgraphsD.AllgraphsaretreesE.NotallgraphshaveaMST

19. TheJacquardLoom(andsimilarmachines)areconsideredinformationtransformers,

butnotcomputers.Whichanswerbestdescribeswhy:A.Programmingthesemachinesdoesn’tscaleB.Programmingthesemachinesrequirespunch-cardsC.MachineslikethesedonothavememoryorcontrolflowD.Machineslikethesearetoooldtobeconsideredcomputers

20. Whenaninstructionisloadedfrommemory,itisdesirabletoloadthecontentsofafewsucceedingmemoryaddressesintothecache.Whyisthat?A.TheCPUisunabletoonlyloadoneinstructionatatimeB.Thosecontentsarelikelytobeusefulintheimmediatefutureaccordingtothe

spatiallocalityprincipleC.Thosecontentsarelikelytobeusefulintheimmediatefutureaccordingtothe

temporallocalityprincipleD.Thecontentsstoredaftertheinstructionarethevaluesusedinthecomputationof

theinstructionandthereforemustbeloadedwiththeinstruction.

21. Thesubset-sumproblemhastimecomplexityO(N*2N).WheredoesthefactorNcomefrom?A:ThatishowmanysubsetsasetofsizeNhas.B:O(N)isthetimecomplexityrequiredtocheckeachpossiblesubsetsum.C:Thatisthetimecomplexityofthealgorithmthatgeneratesthesubsets.D:Noneoftheabove.