CMPS 10 Introduction to Computer Science Lecture Notes

Similar documents
Brave New World Pseudocode Reference

News. Recap: While Loop Example. Reading. Recap: Do Loop Example. Recap: For Loop Example

Agenda & Reading. Simple If. Decision-Making Statements. COMPSCI 280 S1C Applications Programming. Programming Fundamentals

Programming in Fortran 90 : 2017/2018

For instance, ; the five basic number-sets are increasingly more n A B & B A A = B (1)

CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe

Compiler Design. Spring Register Allocation. Sample Exercises and Solutions. Prof. Pedro C. Diniz

Sequential search. Building Java Programs Chapter 13. Sequential search. Sequential search

Assembler. Building a Modern Computer From First Principles.

Harvard University CS 101 Fall 2005, Shimon Schocken. Assembler. Elements of Computing Systems 1 Assembler (Ch. 6)

Virtual Memory. Background. No. 10. Virtual Memory: concept. Logical Memory Space (review) Demand Paging(1) Virtual Memory

9. BASIC programming: Control and Repetition

Lecture 5: Multilayer Perceptrons

Pass by Reference vs. Pass by Value

Complex Numbers. Now we also saw that if a and b were both positive then ab = a b. For a second let s forget that restriction and do the following.

Computer models of motion: Iterative calculations

Introduction to Programming. Lecture 13: Container data structures. Container data structures. Topics for this lecture. A basic issue with containers

CE 221 Data Structures and Algorithms

Assembler. Shimon Schocken. Spring Elements of Computing Systems 1 Assembler (Ch. 6) Compiler. abstract interface.

Midterms Save the Dates!

Exercises (Part 4) Introduction to R UCLA/CCPR. John Fox, February 2005

An Optimal Algorithm for Prufer Codes *

6.854 Advanced Algorithms Petar Maymounkov Problem Set 11 (November 23, 2005) With: Benjamin Rossman, Oren Weimann, and Pouya Kheradpour

Problem Set 3 Solutions

Module Management Tool in Software Development Organizations

CSE 326: Data Structures Quicksort Comparison Sorting Bound

CSE 326: Data Structures Quicksort Comparison Sorting Bound

Assignment # 2. Farrukh Jabeen Algorithms 510 Assignment #2 Due Date: June 15, 2009.

ON SOME ENTERTAINING APPLICATIONS OF THE CONCEPT OF SET IN COMPUTER SCIENCE COURSE

CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar

On Some Entertaining Applications of the Concept of Set in Computer Science Course


Course Introduction. Algorithm 8/31/2017. COSC 320 Advanced Data Structures and Algorithms. COSC 320 Advanced Data Structures and Algorithms

High level vs Low Level. What is a Computer Program? What does gcc do for you? Program = Instructions + Data. Basic Computer Organization

CS1100 Introduction to Programming

Mathematics 256 a course in differential equations for engineering students

CS 534: Computer Vision Model Fitting

5 The Primal-Dual Method

Outline. CIS 110: Intro to Computer Programming. What Do Our Programs Look Like? The Scanner Object. CIS 110 (11fa) - University of Pennsylvania 1

Notes on Organizing Java Code: Packages, Visibility, and Scope

CS221: Algorithms and Data Structures. Priority Queues and Heaps. Alan J. Hu (Borrowing slides from Steve Wolfman)

R s s f. m y s. SPH3UW Unit 7.3 Spherical Concave Mirrors Page 1 of 12. Notes

Intro. Iterators. 1. Access

Parallel Solutions of Indexed Recurrence Equations

Sorting Review. Sorting. Comparison Sorting. CSE 680 Prof. Roger Crawfis. Assumptions

Support Vector Machines

Parallel matrix-vector multiplication

Range images. Range image registration. Examples of sampling patterns. Range images and range surfaces

Midterms Save the Dates!

Load Balancing for Hex-Cell Interconnection Network

Related-Mode Attacks on CTR Encryption Mode

Insertion Sort. Divide and Conquer Sorting. Divide and Conquer. Mergesort. Mergesort Example. Auxiliary Array

Outline. CIS 110: Introduction to Computer Programming. Review: Interactive Sum. More Cumulative Algorithms. Interactive Sum Trace (2)

3D vector computer graphics

TN348: Openlab Module - Colocalization

A Taste of Java and Object-Oriented Programming

Compiling Process Networks to Interaction Nets

The Greedy Method. Outline and Reading. Change Money Problem. Greedy Algorithms. Applications of the Greedy Strategy. The Greedy Method Technique

Oracle Database: SQL and PL/SQL Fundamentals Certification Course

Hermite Splines in Lie Groups as Products of Geodesics

A SYSTOLIC APPROACH TO LOOP PARTITIONING AND MAPPING INTO FIXED SIZE DISTRIBUTED MEMORY ARCHITECTURES

Subspace clustering. Clustering. Fundamental to all clustering techniques is the choice of distance measure between data points;

Concurrent models of computation for embedded software

Today s Outline. Sorting: The Big Picture. Why Sort? Selection Sort: Idea. Insertion Sort: Idea. Sorting Chapter 7 in Weiss.

NAG Fortran Library Chapter Introduction. G10 Smoothing in Statistics

A Binarization Algorithm specialized on Document Images and Photos

Terminal Window. 11. Section 7 Exercises Program Memory Exercise 7-1 Swap Values in an Array Working memory Global Memory. 2 nd call 3 rd call

Overview. CSC 2400: Computer Systems. Pointers in C. Pointers - Variables that hold memory addresses - Using pointers to do call-by-reference in C

Outline. Midterm Review. Declaring Variables. Main Variable Data Types. Symbolic Constants. Arithmetic Operators. Midterm Review March 24, 2014

Sorting. Sorting. Why Sort? Consistent Ordering

GSLM Operations Research II Fall 13/14

Parallelism for Nested Loops with Non-uniform and Flow Dependences

Priority queues and heaps Professors Clark F. Olson and Carol Zander

Searching & Sorting. Definitions of Search and Sort. Linear Search in C++ Linear Search. Week 11. index to the item, or -1 if not found.

Nachos Project 3. Speaker: Sheng-Wei Cheng 2010/12/16

F Geometric Mean Graphs

CHAPTER 2 DECOMPOSITION OF GRAPHS

AMath 483/583 Lecture 21 May 13, Notes: Notes: Jacobi iteration. Notes: Jacobi with OpenMP coarse grain

The Codesign Challenge

Math Homotopy Theory Additional notes

2D Raster Graphics. Integer grid Sequential (left-right, top-down) scan. Computer Graphics

Sorting and Algorithm Analysis

Non-Split Restrained Dominating Set of an Interval Graph Using an Algorithm

Some material adapted from Mohamed Younis, UMBC CMSC 611 Spr 2003 course slides Some material adapted from Hennessy & Patterson / 2003 Elsevier

NUMERICAL SOLVING OPTIMAL CONTROL PROBLEMS BY THE METHOD OF VARIATIONS

Data Representation in Digital Design, a Single Conversion Equation and a Formal Languages Approach

K-means and Hierarchical Clustering

Esc101 Lecture 1 st April, 2008 Generating Permutation

Lecture 3: Computer Arithmetic: Multiplication and Division

Problem Definitions and Evaluation Criteria for Computational Expensive Optimization

Algorithm To Convert A Decimal To A Fraction

Loop Transformations, Dependences, and Parallelization

Introduction. Leslie Lamports Time, Clocks & the Ordering of Events in a Distributed System. Overview. Introduction Concepts: Time

ELEC 377 Operating Systems. Week 6 Class 3

CS240: Programming in C. Lecture 12: Polymorphic Sorting

Transaction-Consistent Global Checkpoints in a Distributed Database System

Design and Analysis of Algorithms

SENSITIVITY ANALYSIS IN LINEAR PROGRAMMING USING A CALCULATOR

Polyhedral Compilation Foundations

Machine Learning. Topic 6: Clustering

Transcription:

CPS 0 Introducton to Computer Scence Lecture Notes Chapter : Algorthm Desgn How should we present algorthms? Natural languages lke Englsh, Spansh, or French whch are rch n nterpretaton and meanng are not deal for ths purpose. We need a more precse notaton to present algorthms that s not subject to dfferng nterpretatons. At the other extreme formal programmng languages (such as C, C++, Java, Perl, ADA, Python, etc.) are very nflexble n ther syntax, and requre much attenton to detal. hese detals may be rrelevant n the ntal desgn phases of an algorthm. Instead we use an nformal and flexble language called pseudo-code whch uses Englsh language constructs and conventons modeled to look lke commands avalable n most computer languages. Detaled & Exact Expressve & Abstract Computer Languages Pseudo-Code Natural Languages Pseudo-code s a language n whch all necessary operatons can be expressed, but whch s ndependent of any computer language, or of any computer for that matter. Sequental Operatons are of three basc knds: computaton, nput, and output. he nstructon for performng a calculaton and storng the result s wrtten as varable expresson hs nstructon tells the computng agent to evaluate the expresson on the rght and assgn ts value to the varable on the left. he left arrow n ths context s called the assgnment operator. Example c a + b + carry Example x b+ b 4ac a Unless otherwse stated, we wll assume that the computng agent s at least as capable as any scentfc calculator, so that the above expressons are consdered prmtve operatons. 5

Input and output operatons allow the computng agent to receve data values from, and send results to the outsde world, whch we also call the user. Computng Agent Input Output Outsde World he operatons used for nput and output are get and prnt respectvely. Example get x Example prnt x Example prnt x + 5 get varable prnt varable prnt expresson ext to be prnted wll be placed n sngle quotes. Example prnt error: dvson by zero Example prnt the value of x s: x and the value of y s: y An algorthm whch uses only sequental operatons s sometmes called a straght lne algorthm. Example ) get a, b, c, d ) sum a + b+ c+ d ) average sum / 4 4) prnt average What does ths algorthm do? Condtonal operatons (also called branchng operatons) are expressed usng the f statement or the f-else statement. he f statement s wrtten as f condton do somethng do somethng do somethng do somethng 6

In ths structure condton stands for a logcal (or Boolean) expresson,.e. an expresson that can be evaluated as true or false. If condton s true, then the ndented lnes are executed, followed by the unndented lnes. If on the other hand condton s false, then the ndented lnes are skpped, and executon pcks up at the next unndented lne. he ndented commands are known as the true branch of the condtonal. An f statement may also come wth an accompanyng else clause. f condton do somethng do somethng else do somethng do somethng do somethng If condton s true, then the frst group of ndented nstructons s executed, and the second group s skpped, followed by the next unndented nstructon. If condton s false, then the frst group s skpped, and the second group of ndented nstructons s executed, followed by the next unndented nstructon. In ths structure the second group of ndented nstructons s known as the false branch of the condtonal, whle the frst group s know as the true branch, as before. Example What does the followng algorthm do? ) get a, b ) f b = 0 ) prnt 'Error: dvson by zero' 4) else 5) quotent a / b 6) prnt quotent 7) stop Iteratve operatons (also called loops) wll be expressed n pseudo-code through three commands: whle, do-whle, and for. whle condton do somethng do somethng do somethng Frst condton s tested, and f found to be true, the ndented lnes (called the loop body) s executed. he condton s tested agan, and f found to be true, the loop body s executed agan. hs process contnues untl the condton s found to be false, n whch case executon pcks up at the next unndented lne. he whle loop condton s sometmes called a loop repetton condton snce the loop body repeats only so long as ths logcal expresson s true. 7

Example What does the followng algorthm do? ) response 'yes' ) whle response = 'yes' ) get a, b 4) f b = 0 5) prnt 'Error: dvson by zero' 6) else 7) prnt a / b 8) prnt 'Do you wsh to contnue?' 9) get response 0) stop he do-whle loop structure puts the loop repetton condton after the loop body. do do somethng do somethng whle condton do somethng Frst the loop body, whch conssts of just those lnes that are ndented, s executed. hen the condton s tested, and f found to be true, the loop body s repeated. We contnue executng the loop body untl condton becomes false, then executon pcks up at the next unndented lne after whle. he loop repetton condton s called a post test condton n ths case snce t s tested after the frst executon of the loop body. he condton n the whle loop on the other hand s called a pre test condton, snce t s tested before the frst executon of the loop body. Example Notce that the loop body n ths example s dentcal to the one n the precedng example. ) do ) get a, b ) f b = 0 4) prnt "Error: dvson by zero' 5) else 6) prnt a / b 7) prnt 'Do you wsh to contnue?' 8) get response 9) whle response = 'yes' 0) stop We often encounter whle loops wth the followng general structure Intalze the loop control varable whle n est the loop repetton condton do somethng wth + Increment the loop control varable 8

We can do these three steps, ntalze loop control varable, test loop repetton condton, and ncrement loop control varable, more succnctly wth the for loop structure below, whch s equvalent to the precedng whle loop. for to n do somethng wth Example Here are two equvalent algorthms, one uses a whle loop, and the other uses an equvalent for loop. A trace of both algorthms would be dentcal. ) ) whle 5 ) prnt 4) + 5) stop ) for to 5 ) prnt ) stop It has been proved that one can represent any vald algorthm wth the operatons so far descrbed. We now consder some well known algorthms whch perform certan basc tasks n computer scence. Example Consder the problem of lookng up a name and correspondng telephone number n a drectory NAE Names Numbers N N N N N n n We assume that the names are n no partcular order (.e. not necessarly n alphabetcal order) so that we must look at each name n successon. If we fnd a name N whch matches our target NAE, we return the correspondng number. If no effect. We call ths algorthm Sequental Search. N s a match, we prnt a message to that Input: n (the number of names n the lst), N, L, N and n, L,n (the lst of names and correspondng telephone numbers), and NAE (the target name we are searchng for.) Output: the telephone number for whch NAE = N, or f no such name exsts, prnt a message to the user. 9

Sequental Search.) Get n, N, K, N n,, K, n, NAE from the user.).) found false 4.) whle n and not found 5.) f N = NAE 6.) found true 7.) prnt 8.) else 9.) + 0.) f not found.) prnt sorry NAE not n drectory.) stop he varable found s called a logcal varable or Boolean varable (named after the Logcan George Boole). It stores one of the two logcal values true or false. A logcal expresson s an expresson whch evaluates to one of these two values. In order to understand how these expressons are evaluated, we must frst defne the logcal operators and, or, and not. A proposton s a statement or asserton whch can (at least n prncple) be evaluated as beng ether true or false. For nstance today s Wednesday and 6< 7 are propostons, whle hello and x < 7 are not propostons. Let A and B be propostonal varables,.e. varables whch stand for unspecfed propostons. We can form the compound propostons A and B, A or B, and not A, usng the operators and, or, and not, whch are defned as follows. A B A and B F F F F F F F In ths truth table, stands for true and F stands for false. In words, A and B s true only n the case when both operands are true, and s false n every other case. A B A or B F F F F F Agan n words, A or B s false only n the case when both operands are false, and s true n every other case. A not A F F hus not A just reverses the logcal value of ts operand A. he operators and and not have the same meanngs that any speaker of Englsh would expect. However there s some ambguty 0

n the Englsh language concernng the word or. he above truth table for or defnes an operaton whch s more properly called nclusve or. It asserts that ether A, or B, or possbly both are true here s another meanng of the word or n the Englsh language called exclusve or, abbrevated exor. hs operaton s defned by the followng truth table. A B A exor B F F F F F F hus A exor B asserts that ether A, or B, but not both are true. Unfortunately for speakers of Englsh, there s no such word as exor, and both meanngs are denoted by the word or. he lstner s expected to gather the meanng from the context. Example A man wth a gun walks up to you and says your money or your lfe. Whch or do you hope he s usng? Fortunately n athematcs and Computer Scence there s no ambguty. Whenever you see the word or used n a ath textbook, t means nclusve or. If we ever mean exclusve or, we explctly wrte exor (or perhaps some other symbol). Now we can see exactly how the logcal expressons on lnes 4 and 0 or Sequental Search wll be evaluated. here are many other examples of searchng problems where the data to be searched s n no partcular order. he algorthmc soluton s essentally the same as that of the phone book example,.e. step through the data from begnnng to end untl the target data tem s found. It s conceptually very useful and elegant to consder all these examples as beng dfferent nstances of the same problem, all solvable by the same algorthm. Snce everythng n Computer Scence s ultmately represent able by numbers, we can present ths Generalzed Sequental Search algorthm as a search of an unsorted lst of numbers for some target number. Input: n (the number of numbers n the lst), a,,an (the number to search for.) Output: he frst ndex such that Sequental Search.) Get n, a, K, an, target from the user.).) found false 4.) whle n and not found 5.) f a = target 6.) found true 7.) else 8.) + 9.) f not found 0.) 0.) prnt.) stop L (the lst of numbers tself), and target target = a, or 0 f no such ndex exsts.

Example race ths algorthm on the nput: n = 5, target =, and the lst, -,, 5,. Exercse odfy ths algorthm to fnd the last (.e. rghtmost) occurrence of the target. How can we modfy t to fnd the nd, or 5 th, or j th occurrence of the target? How can we modfy t to prnt the number of occurrences of the target? Another common problem n processng a lst of numbers s to fnd the largest or smallest number n the lst. he followng algorthm, called Fnd Largest, solves ths problem. Input: n (the number of numbers), and a, L,an (the lst of numbers, whch we assume to be dstnct). Output: he largest value n the lst, together wth the poston (.e. the ndex ) where t s located. Fnd Largest.) max a (max s the largest value seen so far).) j (j s the ndex of the largest value seen so far).) ( s the ndex of the element we are presently lookng at) 4.) whle n 5.) f a > max 6.) max a 7.) j 8.) + 9.) prnt max, j 0.) stop Example race ths algorthm on the lst,, -7, 5,,, 0. Exercse What happens f we run Fnd Largest on a lst whose elements are not dstnct? ry t on the lst,, 0, 0,, 5, 0. How can t be modfed to fnd all occurrences of the maxmum? How can t be modfed to fnd the mnmum? Exercse Assume that addton of ntegers s a prmtve operaton for the computng agent, but that multplcaton of ntegers s not. Wrte an algorthm whch takes as nput two (non-negatve) ntegers a and b, and prnts out ther product a b. Obvously one cannot wrte prnt a b snce we are assumng here that multplcaton s not prmtve. he problem s to defne multplcaton algorthmcally n terms of repeated addton, as follows..) get a, b.) product 0.) 4.) whle b 5.) product product+ a 6.) + 7.) prnt product 8.) stop

hs algorthm could be wrtten a lttle more succnctly usng a for loop..) get a, b.) product 0.) for to b 4.) product product+ a 5.) prnt product 8.) stop Exercse Now assume that multplcaton s a prmtve operaton for the computng agent, but that exponentaton (.e. rasng a number to a power) s not. Wrte an algorthm whch takes as b nput two (non-negatve) ntegers a and b, then prnts out the value a. Agan t s obvous that b statement prnt a s not a vald operaton. he problem s to defne exponentaton n terms of repeated multplcaton. A classcal problem n Computer Scence s Pattern atchng. here are many versons of ths problem dealng wth patterns n graphcs, sound, pctures, and other types of data. We wll consder a smple form of ths problem: fndng patterns n text data. ore precsely, gven n characters of text KKKKKKKKK n and gven a pattern of m characters, where m n P P P KK P m fnd every occurrence of the pattern wthn the text,.e. fnd each ndex poston n the text at whch the pattern begns. Example n = 8, m= text: to be or not to be pattern: be answer: 4, 7 Example n = 0, m= text: xxxaaaaaxx pattern: aaa answer: 4, 5, 6 Notce that f m =,.e. f the pattern has just one character n t, then ths problem s not essentally dfferent from the searchng problem. We may expect that our algorthm wll show some smlarty to Sequental Search. Our soluton wll be to smply compare the pattern, one character at tme, to m contguous text characters at every possble startng locaton wthn the text. We start by comparng P to, and f they match compare P to, and f they match compare P to, etc. We contnue n ths manner untl reach the end of the pattern and thus establsh that the pattern matches the text at poston, or untl we fnd two characters whch don t match, ndcatng a msmatch at poston. We then slde the pattern over one poston n

the text and compare P to, then P to, etc. as before untl we ether establsh a match or a msmatch at poston n the text. Every tme a match occurs, we prnt out the ndex wthn the text at whch the pattern and text matched. Example n = 7, m= check for match at poston = 4 5 6 7 P P P slde over = 4 5 6 7 P P P = 4 5 6 7 P P P = 4 4 5 6 7 P P P = 5 4 5 6 7 P P P In ths case we see that the possble answers,.e. the set of possble ndces at whch a match can occur, are = to = 5, snce to slde the pattern over one more tme would cause t to fall off the end of the text. In general the ndces to be tested range from = to = n m+. Input: Integers n and m satsfyng m n, the text KKKn to be searched, and the pattern P P P KPm to search for. Output: All ndces such that P P P KPm matches + + K + m. Pattern atch.).) whle n m+.) j 4.) match true 5.) whle j m and match 6.) f P j + j 7.) match false 8.) else 9.) j j+ 0.) f match.) prnt match found at poston.) +.) stop 4

Exercse race ths algorthm on some smple examples lke to be or not to be or xxxaaaaaxx above. Search for varous patterns wthn these texts. Exercse How can ths algorthm be used to fnd words rather than patterns? For nstance consder the text hand the band to randy and I, and search for the pattern and. he answers wll be postons,, 8, and. However the word and appears only once, at poston. How can we use ths algorthm to fnd only the word and and not all occurrences of the pattern and wthn other words? 5