Title: CptS 355 Programming Language Design
1CptS 355Programming Language Design
Control 2 Repetition and Invariants
- Roger Ray
- WSU Vancouver, Spring 2001
control2.ppt
2Coming Events
- How to write a good loop
- building loops
- optimizing loops
- Language design issues
- arrays loops
- Assignments
- rwb - "Red, White, and Blue" lab, due 2/21
- good - "Good Sequences" lab, due 2/21
- plural - due today, graded and returned 2/14
- Puzzles and Jargon
- some fun before class
read the text focus on main ideas (see a
following slide)
on website,see packets puzzle.ppt and
jargon.ppt, which are occasionally updated
current puzzle fork in road
3Notation for Making Array Assertions
- Pictures to show state
- all subarrays ("zones", "regions") can be empty
unless explicitly stated otherwise - be crisp but complete
- use ASCII art in your code
- Math notation to describe state
- 0 ? i ? 5 value of i is in range 0 thru 5
inclusive - b lt 3 all elements of b are less than 3
- min b minimum value in array b (-infinity if
empty) also "max", "sum", ... - bi..j the subarray of array b from bi thru
bj inclusive (empty if i gt j) - i st bi v i is some value such that bi v,
i undefined if no such i - i st bi v else i -1 i such that bi v,
if possible, otherwise such that i -1 - symbolic logic represent math symbols via "",
"", "for all", "for some", etc.
0
n-1
lt v
gt v
b
lo
hi
------------------------ lt v
gt v ------------------------ 0 lo
hi n-1
4Building Loops
blank sheet of paper
well structured loop
??
pre-condition
initial situation
?
establish invariant
?
while (! termination-condition )
?
make progress towards the termination-condition wh
ile maintaining the invariant
?
goal situation
??
post-condition
- Steps for building a well-structured loop
- clearly state pre-condition and post-condition
- define an invariant partway between the
conditions and establish it from the
pre-condition - define a termination-condition such that
invariant ? termination-condition ?
post-condition - specify a loop action that always makes progress
toward termination and maintains invariant - confirm common and extreme situations are handled
by simulation with concrete data
5Example Loops
- Find max value in an array
- Merge two arrays
- Find value using binary search
- Partition an array
- Sort an array
61. Find Max Value in an Array
- Given
- x is int array length at least 1
- Goal
- set r to max value in x
- Checklist
0
n-1
x
72. Merge Two Arrays
0
m-1
- Given
- x, y, and z are int arrays x and y are input z
is output - x and y are sorted in ascending order might be
empty - Goal
- set z to merge of x and y, preserving order and
all values - set k to number stored
- Checklist
sorted ascending
x
n-1
sorted ascending
y
mn-1
z
8Optimizing Loops
- Easy Move computation outside of loop
- accumulate a result incrementally
- introduce new variables to hold repeated or
constant values - Beginner Reduce complexity of termination and
other tests - add sentinel values
- manipulate invariant
- handle special cases elsewhere
- Expert Make faster progress towards termination
- take several steps inside loop
- look for better algorithm or data structure
- unroll the loop
9Optimizing Merge Using Sentinels
0
m-1
- Given
- x, y, and z are int arrays x and y are input z
is output - x and y are sorted in ascending order might be
empty - values in range ? 1000000 extra room at end of
each array - Goal
- set z to merge of x and y, preserving order and
all values - set k to number stored
- Checklist
sorted ascending
x
n-1
sorted ascending
y
mn-1
z
10Variant Merge Two Arrays Without Repeats
0
m-1
- Given
- x, y, and z are int arrays x and y are input z
is output - x and y are sorted in ascending order might be
empty may have repeated values - Goal
- set z to merge of x and y, preserving order but
do NOT repeat values - set k to number of values stored in z
- Notes
- assume room and domain for sentinel values (xm,
yn, z-1, zmn) - Checklist
sorted ascending
x
n-1
sorted ascending
y
mn-1
to be overwritten
z
Good test question!
113. Find Value Using Binary Search
- Given
- x is int array might be empty in ascending
order no repeated values - Goal
- p st xp v else p -1
- Checklist
0
n-1
sorted ascending
x
v a value perhaps in x
12Optimizing Binary Search Using New Invariant
- Given
- x is int array might be empty in ascending
order no repeated values - Goal
- p st xp v else p -1
- Checklist
0
n-1
sorted ascending
x
v a value perhaps in x
134. Partition an Array
0
n-1
- Given
- x is int array non-empty may not be sorted
- v is some value might not be in x
- Goal
- m st x0..m-1 lt v ? xm..n-1 ? v
- obviously x may need reordering but, do this
without an extra array - Checklist
x
v a value
0
n-1
lt v
? v
x
m
145. Sort an Array
- Given
- x is int array might be empty unordered
- Goal
- sort x in place using selection sort
- Checklist
0
n-1
x
- selection sort process
- repeat n times
- remove min element from unsorted zone
- add the min to the sorted zone
Good test question!
155. Sort an Array
0
n-1
sorted
not yet sorted
x
invariant
m
termination
m n
code
void sort (int x, int n) int m 0 while (m
lt n) // set k st xk is min xm..n-1 int k
m for (int i k1 i lt n i) if (xi lt xk)
k i // swap xm and xk int t xm xm
xk xk t // reduce size of unsorted
zone m
16Loop Language Designs
The "while" loop is sufficient!
But, some forms are so common, designers have
invented abbreviations ...
- Counter-controlled loops ("for loops")
- Multiple-exit loops ("breaks")
- Provable-programs ("guards")
17Counter-Controlled Loops
- Various approaches
- Good C practice code as if language Algol
- What are the most common coding errors?
18Multiple-Exit Loops
- Situation occurs when termination-condition has
form x or y - Many weird approaches
- Some possible approaches in C
e.g. Ada, page 313
enum Unknown, X, Y int outcome
Unknown while (outcome Unknown) if (x)
outcome X else if (y) outcome Y else ...
make progress ... if (outcome X) ... handle
... else ... handle ...
while ( !x !y ) ... make progress ... if
(x) ... handle ... else ... handle ...
while (1) if (x) ... handle ... break if
(y) ... handle ... break ... make progress
...
- see "Good" lab solution for how I like tocode a
very common case. - avoid "continue" and hidden "break"s
- avoid "post-test" (do ... while)
19Guards
Motivation control constructs that allow
mathematical proof techniques to be applied to
source code
- Dijkstra introduced "guarded commands"
- These allow non-determinism in the control flow
- any statement with true guard will be executed
- this matches mathematical definition of "minimum"
- thus, mathematical proof techniques easier to use
- other languages over-specify the control flow
- note what is the semantics of this?
- // set m to min (x, y)
- if x ? y ? m x
- y ? x ? m y
- fi
if fi
- // set x to gcd (A, B)
- x, y A, B
- do x gt y ? x x - y
- y gt x ? y y - x
- od
- any statement with true guard will be executed
- continues until all are false
- note what is the semantics of this?
do od
the classic references "A Discipline of
Programming", Edsger Dijkstraand "The Science of
Programming", David Gries
20Main Ideas in the Reading
- Arrays
- () vs notation which languages advantages
of each - storage management possible approaches
advantages of each - subscripts dimensionality, restrictions on
subscripts, Pascal approach - initialization C and Java approach (both
static and dynamic) - operations APL approach
- slices syntax, meaning, languages
- implementation 2D layouts, C 1D approach,
Java differences vs. C - associative usefulness, Perl approach (later a
C approach)
- Counter controlled loops
- why bother with these?
- variants their properties (esp. Fortran, Algol,
C) - what are most common coding errors?
- Logically controlled loops
- sufficiency of while loop
- pre-test vs. post-test when use?
- multiple exit loops how simulate in C?
- foreach Perl approach (later a C approach)
Lecture will focus only on issues that might be
unclear and those that you ask about
21Labs
22Assignment Red, White, and Blue
Due 2/21
You must program a robot to rearrange the balls
stored in a series of bins
- Initial state
- each bin contains exactly one ball
- each ball is either red, white, or blue
- the balls are randomly arranged
- Goal state
- all red balls are in leftmost bins
- then white balls
- then finally blue balls in rightmost bins
- Robot has two tools for you to use
- eye - can report color of ball in a specified bin
- arm - can swap the balls in two specified bins
- Rules
- you cannot ask for a color of a ball more than
once! - you cannot use a array to remember anything!
- you must handle all extreme cases!
- Coding details on next slide ...
0
n-1
red, white, blue balls
red white
blue
23Coding Details
- You code a procedure "arrange" that arranges the
balls as needed (use C) - I supply a "main.o" with a test driver that calls
"arrange" - The robot routines for you to use are also in
"main.o" - I supply these files
- rwb.h -- include file with interfaces (see below)
- main.o -- test driver and robot routine
implementations - input.txt -- test cases for test driver to read
- You submit these files
- arrange.cpp -- implements "arrange"
- Grading will focus on
- loop implementation (structure, efficiency)
- overall clarity (names, comments, annotations)
rwb.h
// Define ball colors enum Color RED, WHITE,
BLUE // Return color of ball in bin i extern
Color content (int i) // Swap balls in bins i
and j extern void swap (int i, int j) //
Arrange balls in n bins (you code this) extern
void arrange (int n)
how you work
copies supplied files to .if needed see
lab guidelines
class cs355 lab rwb g -c arrange.cpp
g -o rwb main.o arrange.o rwb lt input.txt
submit
24Assignment Good Sequences
Due 2/21
Tabulate the number of "good" sequences of
various lengths
- Context
- we consider sequences of 1's, 2's and 3's max
length n is 0 lt n lt NMAX - we call a sequence "good" if it has no adjacent
non-empty subsequences that are the same - we want to consider all possible sequences in
"lexicographic" (alphabetic) order - we want to tabulate the number of good sequences
of each length from 0 thru n - Coding details
- see next slide
- good 3
- 0 1
- 3
- 6
- 12
- ----------
- total 22
Challenge plot the numbers you get for "good 6"
and make a hypothesis
25Coding Details
// Determine if s0..k-1 is good. // s0..k-2
is known to be good. // s-1 is 1. extern int
isGood (int s, int k) // Update s per
lexicographic rules. // Current length is k max
length is n. // mode selects the update rule //
mode 1 next in order, any length // mode
0 next with length lt k // Return length of
new sequence. // Return 1 if no more
sequences. extern int next (int s, int k,
int n, int mode)
good.h
- I supply these files
- main.o -- main routine and test driver
- good.h -- interface to your routines
- logic.txt -- a questionnaire
- You submit these files
- good.cpp -- routines you implement
- logic.txt -- completed questionnaire
- You implement these routines
- isGood -- tests if a sequence is good
- next -- updates sequence to next one
- You work as shown below
main.cpp
int main (...) int verbose ... from command
line ... int n ... from command line ... int
t new intn1 // t array length n1 int s
t1 // s array length n, s-1 ok s-1 1
// sentinel value int k 0 while (k ! -1)
if (isGood (s, k)) if (verbose) ... print
s0..k-1 ... ... increment count for k length
... k next (s, k, n, 1) // next, maybe
longer else k next (s, k, n, 0) // next,
but no longer ... print all counts ...
how you work
class cs355 lab good g -c good.cpp g
-o good main.o good.o good v 3 submit
- good args
- 3 n (required, lt 10)
- -v verbose (optional)
26Content of Logic.txt
- Complete the supplied file to describe your logic
in your "good.cpp"
logic.txt
Name your name A sequence s0..k-1 is good
when symbolic logic statement If s0..k-2 is
known to be good, the above can be simplified
to optimized logic statement The pre-condition
for my loop in the "next" routine is symbolic
logic statement The invariant for the loop
is invariant statement The post-condition
is symbolic logic statement
remember to describe any free variables that
appear in your logic statements