Brave New World Pseudocode Reference

Similar documents
CMPS 10 Introduction to Computer Science Lecture Notes

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.

Intro. Iterators. 1. Access

Programming in Fortran 90 : 2017/2018

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

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

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

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

Mathematics 256 a course in differential equations for engineering students

Computer models of motion: Iterative calculations

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

CE 221 Data Structures and Algorithms

A Binarization Algorithm specialized on Document Images and Photos

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

Midterms Save the Dates!

Problem Set 3 Solutions

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

CSE 326: Data Structures Quicksort Comparison Sorting Bound

CS1100 Introduction to Programming

CSE 326: Data Structures Quicksort Comparison Sorting Bound

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

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

Sorting: The Big Picture. The steps of QuickSort. QuickSort Example. QuickSort Example. QuickSort Example. Recursive Quicksort

USING GRAPHING SKILLS

Array transposition in CUDA shared memory

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

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

The Codesign Challenge

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

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

9. BASIC programming: Control and Repetition

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

CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe

Midterms Save the Dates!

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

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

Sorting and Algorithm Analysis

Parallelism for Nested Loops with Non-uniform and Flow Dependences

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

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

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

MATHEMATICS FORM ONE SCHEME OF WORK 2004

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

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

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

Lecture 3: Computer Arithmetic: Multiplication and Division

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

Algorithm To Convert A Decimal To A Fraction

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

Support Vector Machines

Report on On-line Graph Coloring

Setup and Use. Version 3.7 2/1/2014

5.1 The ISR: Overvieui. chapter

Esc101 Lecture 1 st April, 2008 Generating Permutation

An Optimal Algorithm for Prufer Codes *

K-means and Hierarchical Clustering

Improving Low Density Parity Check Codes Over the Erasure Channel. The Nelder Mead Downhill Simplex Method. Scott Stransky

Quicksort. Part 1: Understanding Quicksort

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

CS 534: Computer Vision Model Fitting

Kent State University CS 4/ Design and Analysis of Algorithms. Dept. of Math & Computer Science LECT-16. Dynamic Programming

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

such that is accepted of states in , where Finite Automata Lecture 2-1: Regular Languages be an FA. A string is the transition function,

ELEC 377 Operating Systems. Week 6 Class 3

Setup and Use. For events not using AuctionMaestro Pro. Version /7/2013

Assembler. Building a Modern Computer From First Principles.

Lecture #15 Lecture Notes

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

SENSITIVITY ANALYSIS IN LINEAR PROGRAMMING USING A CALCULATOR

Design and Analysis of Algorithms

Pass by Reference vs. Pass by Value

The example below contains two doors and no floor level obstacles. Your panel calculator should now look something like this: 2,400

Parallel Numerics. 1 Preconditioning & Iterative Solvers (From 2016)

Lecture 5: Multilayer Perceptrons

GSLM Operations Research II Fall 13/14

Load Balancing for Hex-Cell Interconnection Network

Wightman. Mobility. Quick Reference Guide THIS SPACE INTENTIONALLY LEFT BLANK

Machine Learning: Algorithms and Applications

ECONOMICS 452* -- Stata 11 Tutorial 6. Stata 11 Tutorial 6. TOPIC: Representing Multi-Category Categorical Variables with Dummy Variable Regressors

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

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

Life Tables (Times) Summary. Sample StatFolio: lifetable times.sgp

Analysis of Continuous Beams in General

with Optic65 and Optic25 Cameras FOR OUTDOOR TRACKING ONLY unless used in conjunction with the Indoor Tracking Accessory.

Optimization Methods: Integer Programming Integer Linear Programming 1. Module 7 Lecture Notes 1. Integer Linear Programming

A mathematical programming approach to the analysis, design and scheduling of offshore oilfields

Meta-heuristics for Multidimensional Knapsack Problems

CHAPTER 10: ALGORITHM DESIGN TECHNIQUES

Announcements. Supervised Learning

Edge Detection in Noisy Images Using the Support Vector Machines

LOOP ANALYSIS. The second systematic technique to determine all currents and voltages in a circuit

Module Management Tool in Software Development Organizations

LLVM passes and Intro to Loop Transformation Frameworks

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

VRT012 User s guide V0.1. Address: Žirmūnų g. 27, Vilnius LT-09105, Phone: (370-5) , Fax: (370-5) ,

Machine Learning. Topic 6: Clustering

VISUAL SELECTION OF SURFACE FEATURES DURING THEIR GEOMETRIC SIMULATION WITH THE HELP OF COMPUTER TECHNOLOGIES

Why visualisation? IRDS: Visualization. Univariate data. Visualisations that we won t be interested in. Graphics provide little additional information

User Authentication Based On Behavioral Mouse Dynamics Biometrics

Oracle Database: SQL and PL/SQL Fundamentals Certification Course

Transcription:

Brave New World Pseudocode Reference Pseudocode s a way to descrbe how to accomplsh tasks usng basc steps lke those a computer mght perform. In ths week s lab, you'll see how a form of pseudocode can be used to program the Scrbbler robot. The Scrbbler control panel has a pont and clck nterface, but n the rest of the course you wll wrte your own smple pseudocode to express computatons. The advantage of pseudocode over plan Englsh (as you saw n case of scrbbler) s that t has a precse meanng. The exact syntax s not too mportant what counts s expressng a computaton clearly and precsely. You can use the handout below for all your homework and on the exam. Varables In pseudocode you wll need to use varables to store data. You can thnk of these as lttle boxes that hold a number, and you are allowed to look at what s n the box or replace ts contents wth somethng else. We call whatever s nsde the box the value of the varable. An array s a shorthand way of namng a bunch of varables. If A s an array of length n, you can magne t as n boxes lned up n a row. Then we wrte A[] to refer to the th box. Here s a pcture of what A mght look lke n memory: A = 40.0 6.71 5.54.05 You can use arrays n pseudocode nstructons the same way you use varables: x A[] Sets x to the second value n the array A (here, 6.71) A[3] Sets the thrd value n the array A to the value (replacng 5.54) Sometmes you wll use a varable to specfy whch element of the array you mean: y A[] Sets y to the th array value Arrays can be multdmensonal. Whle a one-dmensonal array s lke a lst, a twodmensonal array s lke a grd. If A s a two-dmensonal array, A[][j] refers to the value n row, column j of the grd.

Instructons A pseudocode program s wrtten as a seres of nstructons that the computer executes one at a tme. These are several knds of nstructons: Arthmetc Instructons Arthmetc nstructons affect values stored n varables, named peces of memory. These nstructons take the form varable arthmetc expresson. For example: x 5 Sets the value stored n varable x to the value 5 y x Sets y to the value stored n x; leaves x unchanged j + 1 Sets to the value j + 1; leaves j unchanged There are only a few arthmetc operatons allowed, these are addton, subtracton, multplcaton, and dvson. Note that exponentaton, logarthms, and more complex operatons are not basc. Two useful operatons that are a lttle non-standard but that you may also use are the celng and floor operators. cel(x) denotes the smallest nteger greater than or equal to x. For example, cel(3.4) = 4, cel(4.1) = 5, cel() =. floor(x) s defned analogously as the greatest nteger less than or equal to x. (Note: The Scrbbler doesn t support all pseudocode nstructons. For nstance, t does not understand arthmetc nstructons, varables, or arrays.) Smple actons Sometmes you can use a sngle nstructon to specfy a behavor. E.g.: Move forward for 1s Read the prce from the next jar Place the box back on the shelf. Use nstructons lke these for actons that are secondary to your program s purpose. Condtonals Condtonal ( branch ) nstructons perform one set of actons only f some specfed condton s true and another set only f the condton s false. They take ths form: If true/false condton Then Frst lst of nstructons Else Second lst of nstructons

(You can omt the Else branch f you don t want to take any specal acton when the condton s false.) Here s a smple example: If x s odd Then x x 1 count count + 1 Else x x Ths condtonal checks whether x s odd. If so, t subtracts one from x and adds one to count; otherwse, t dvdes x by two. It s mportant to understand that the true/false condton s checked only once, at the begnnng of the condtonal. If x s odd, the computer subtracts one from x, makng t even. However, the computer does not go on to dvde x by two. Loops Loops perform a set of actons some number of tmes. One knd of loop performs an acton over and over agan nfntely (or at least untl the computer or robot s turned off). These look lke ths: Do forever Lst of nstructons Another flavor of loop makes the computer follow a seres of nstructons a fxed number of tmes. For example: Do for n tmes Lst of nstructons A thrd knd of loop adds a varable that counts the passes through the loop: Do for = a to b Lst of nstructons On the frst pass, the varable s set to a. At the start of each successve pass, s ncreased by one, untl on the fnal pass t has the value b. In all, the computer 3

performs the lst of nstructons b a + 1 tmes. You could use such a loop to add the ntegers from 1 to 100 (nclusve) as follows: sum 0 Do for = 1 to 100 sum sum + The last knd of loop makes the computer perform some nstructons repeatedly as long as a specfed condton remans true. It takes the form: Do whle true/false condton Lst of nstructons At the begnnng of the loop, the computer checks whether the condton s true. If so, t executes the lst of nstructons. Then t checks agan whether the condton s true; f so, t executes the nstructons agan. Ths process s repeated untl the computer checks the condton and t s false. Here s an example: Do whle current < max current current + 1 Other nstructons What happens f current max the frst tme the computer evaluates the Do whle nstructon? In ths case, the operatons nsde the loop are not executed at all. Input and Output Sometmes you want to get values from outsde the program. For example: Get prce Sets the varable prce to a value from outsde the program Smlarly, your program can present ts results usng nstructons lke these: Prnt The lowest prce was: Dsplay a fxed message Prnt mnmum Dsplay the value of the varable mnmum Comments Comments are not actually nstructons; nstead, they provde hnts about what the program does to help humans understand t. A comment begns wth two slashes // and contnues untl the end of the lne, for example: f (9/5) * c + 3 // Convert Celsus to Fahrenhet Remember, comments don t change the meanng of your program, snce computers skp over them entrely. They do help make the meanng clearer to human readers. Caveat 4

Pseudocode looks deceptvely lke Englsh, and that s ts advantage: t should be understandable by your average lay-person. However, please be aware of the dfferences between pseudocode and plan Englsh: pseudocode s meant to be executed verbatm, and not nterpreted wth human common sense. For example, a condtonal statement s executed only once, whereas a loop s repeated. Understandng pseudocode Just as a chld frst learns to understand language, and then to speak, and fnally to wrte, you also should frst learn to understand pseudocode wrtten by others and only then attempt to wrte your own. In order to understand pseudocode, you don t just read t as you would a poem or a novel. You work through t. You take a blank sheet of paper, desgnate some space on the paper for the varables, arrays etc. Then you execute the pseudocode lne by lne on ths data. After you do ths a few tmes, you begn to understand what t does. Example 1: Vote countng machne We llustrate ths wth the followng program that counts votes for two canddates. Votes for canddate 1 or canddate are read one by one. Let s assume that the votes are gven to us n an array A, and that there are n votes total. Let s also assume for smplcty that each vote s stored as ether 1 or. 1 // Set ntal vote counts to zero 0 // holds the tally for canddate 1 3 0 // holds the tally for canddate 4 Do for = 1 to n 5 6 // See who the next vote s for 7 If A[ ] = 1 then 8 9 // If t s for canddate 1, then ncrement hs tally 10 + 1 11 1 else 13 14 // Otherwse t s for canddate, so ncrement hs tally 15 + 1 16 17 18 Prnt Totals:,, 5

Let s work through an example wth ths pseudocode and see exactly what happens when we execute t. Suppose n = 5 and we have the followng data n an array A. We have our two varables to keep a tally and, and our loop varable. We wll ntalze and to 0, and the frst tme through the loop we have = 1, whch we wll depct as pontng to the frst spot n A. Thus at the begnnng of the frst loop the pcture looks lke ths: 1 0 0 Now we look to see f A[ ] = 1. In ths case t s ndeed, so we ncrement. 1 1 0 Now we loop around and ncrement, whch gves us the pcture 1 0 We check whether A[ ] = 1, whch t s, so we ncrement agan. 6

0 Then we ncrement agan to get 3 0 We check f A[ ] = 1, and n ths case t s not, so we ncrement. 3 1 Then we ncrement and repeat two more tmes. At the end, our pseudocode wll gve us somethng that looks lke: 5 3 Example : Sortng a lst of numbers Ths program sorts a lst of n numbers usng the selecton sort method dscussed n lecture. Notce how comments make the program easer to understand. 1 // Input n and the lst of numbers, whch are stored n the array A 7

Get n, A[1],, A[n] 3 Do for = 1 to n-1 4 5 // Search from poston to poston n n the array; fnd the mnmum value, 6 // and record ts poston n best. 7 best 8 Do for j = +1 to n 9 10 If A[] < A[best] then 11 1 best 13 14 15 // Swap the mnmum value (A[best]) wth the 'th value 16 tmp A[best] 17 A[best] A[] 18 A[] tmp 19 0 Prnt A[1],, A[n] 1 END Example 3: The Game of lfe Ths example smulates rounds n the Game of Lfe. The programs starts by gettng the number of rounds to smulate (t), the sze of the square grd (n) and the ntal state of the grd (the array A). A grd value of 1 ndcates an occuped square, and 0 ndcates an unoccuped square. In every round, the program apples the rules of the game to each square to determne whether the square wll be occuped n the next round. At the end of the round, the next round state (array B) replaces the current round state (array A). 1 // Input the number of rounds, the sze of the grd, and the ntal state of the grd Get t, n, A[1][1], A[1][],, A[n][n] 3 Do for step = 1 to t 4 5 // On each round, examne every grd square 6 Do for = 1 to n 7 8 Do for j = 1 to n 9 10 // Count neghbors by addng all adjacent squares 11 neghbors A[-1][j-1] + A[-1][j] + A[-1][j+1] + A[I ][j-1] + A[ ][j+1] + A[+1][j-1] + A[+1][j] + A[+1][j+1]; 1 // Determne f current square wll be occuped n the next round 13 If A[][j] = 1 then 8

14 15 If neghbors = or neghbors = 3 then 16 B[][j] 1 // Survval 17 Else 18 B[][j] 0 // Death 19 0 Else 1 If neghbors = 3 then 3 B[][j] 1 // Brth 4 5 6 // Update the grd wth the next round s state 7 Do for = 1 to n 8 9 Do for j = 1 to n 30 31 A[][j] B[][j] 3 33 34 35 // Output the fnal state of the game 36 Prnt L[1][1], L[1][],, L[n][n] 37 END (Notce that ths program sn t correct for the squares at the corners and edges of the grd, whch don t have 8 neghbors. How would you fx ths?) Suggestons for wrtng your own pseudocode Unfortunately there s no one way to convert an dea of an algorthm nto a pseudocode. (Thnk about t, ths would n essence be an algorthm for wrtng algorthms!) But to get you ponted n the rght drecton, here are several general gudelnes that wll help you n wrtng your own pseudocode. Let s thnk agan about Example 1: the vote countng machne. Remember our goal: count all the votes and then prnt out the number of votes for each canddate. Let s thnk about how to wrte the pseudocode for ths task. Ponts to consder when thnkng about the algorthm: 1. Imagne gvng your program to a 7-year old who can understand Englsh and do elementary arthmetc but doesn t have much common sense or experence. He or she should be able to understand exactly what to do gven your pseudocode. 9

. Your program should work for arbtrarly long nput, n ths case arbtrarly many votes. Thus, although sayng Just count the votes mght make sense for 10 votes, f you are gven 10,000,000,000 votes then t s not as obvous what Just count the votes means. 3. Remember that the nstructons are executed step by step. Whoever s runnng your program s not allowed to look at the program as a whole to guess what you actually meant t to do. Wth these ponts n mnd, let s thnk about how to count votes. Say we are gven the votes n a bg ple. One way to count would be: Idea A: Take the frst vote, see who t s for. If t s for canddate 1 then mark a tally for 1, or f t s for then mark a tally for. Then keep repeatng ths for the rest of the votes untl you go through the entre ple. Ths s the dea (or the algorthm). Now we need to turn t nto pseudocode. Ponts to consder when you are tryng to turn an dea nto pseudocode: 1. What knd of nformaton s recorded n the process of dong the task? Ths nformaton wll have to be stored n varables when you wrte the pseudocode.. Where do you make decsons about selectng one of two actons to do? These wll usually become condtonal statements n the pseudocode. 3. Where do you repeat thngs? These wll become loops n the pseudocode. OK now let s look at Idea A and try to translate t nto pseudocode. 1. What are we keepng track of? The talles of votes for each canddate. Thus, these two talles wll become varables n the pseudocode.. Where do we make a decson between two actons? When we decde whch canddate s tally we should add to. Ths wll become a condtonal statement. 3. Where do we repeat? When we are done wth one vote we move on to the next and repeat the same procedure. Gong through the ple of votes s lke loopng through an array, where each element tells us someone s vote. Now f you go back and look at the pseudocode for Example 1, you ll see exactly how the dea was transformed nto pseudocode. Also, remember that there s more than one way to wrte pseudocode for the same algorthm, just lke there s more than one way to express the same dea n Englsh. 10

How fast does your algorthm run? The central measure of goodness of an algorthm (assumng t does ts job correctly!) s how fast t runs. We want a machne-ndependent measure and ths necessarly mples we have to sacrfce some precson. In general, the relatve speeds of arthmetc operatons (+, * etc.) dffer among machnes, but we wll assume all of them take the same amount of tme. The three central ponts to remember when dscussng runnng tme are: 1. Even though we call the speed of an algorthm ts runnng tme, we won t actually measure t n seconds or mnutes, but n the number of elementary operatons t takes to run. For ths class, elementary operatons are arthmetc (addton, subtracton, multplcaton, dvson), assgnng a value to a varable, and condton checks (ether n an f statement or n a do statement).. The runnng tme n general depends on the sze of the nput. For example, f we are sortng an array of n elements, t s natural (and unavodable) that t wll take longer to sort n = 10,000,000 elements than to sort n = 10 elements. 3. We wll usually analyze worst-case runnng tme. That s, how long wll ths algorthm run gven the worst possble nput of sze n? Whenever n doubt, we err on sde of overestmaton rather than underestmaton. Let s analyze the runnng tme n Example 1. 1 // Set ntal vote counts to zero votes_for_canddate_1 0 3 votes_for_canddate_ 0 4 Do for = 1 to n 5 6 // See who the next vote s for 7 If A[ ] = 1 then 8 9 // If t s for canddate 1, then ncrement hs tally 10 votes_for_canddate_1 votes_for_canddate_1 + 1 11 1 else 13 14 // Otherwse t s for canddate, so ncrement hs tally 15 votes_for_canddate_ votes_for_canddate_ + 1 16 17 18 Prnt Totals:, votes_for_canddate_1, votes_for_canddate_ 11

It takes steps to ntalze the varables. Then we run the loop n tmes: each tme, we check 1 condton (.e. who the vote s for) and possbly make 1 assgnment (.e. ncrementng the tally). Thus each tme we go through the loop we execute at most steps. Fnally t takes 1 step at the end to prnt the results. Thus addng everythng up the algorthm runs n tme n + 3. 1