Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

141: Reasoning about Programs

Substring Search in one Loop - 2nd Part Individual Hand-in on 6th March, by 13:00
Sophia Drossopoulou

Learning Aims: to practice reasoning using invariants and lemmas. Consider the following denitions. M atch(s, t, m, n) 0 m+n s.length 0 n t.length ( k [0..n) : s[m+k] = t[k] ) F ind(s, t) = s.length min{ m | M atch(s, t, m, t.length) } if m.M atch(s, t, m, t.length) otherwise

The following properties hold (no need to prove them), for all strings s and t, and integers m, n and n : Lemma 0 Lemma 1 Lemma 2 Lemma 3 Lemma 4 0 n n M atch(s, t, m, n) M atch(s, t, m, n ) 0 m s.length M atch(s, t, m, 0) t.length = 0 F ind(s, t) = 0 F ind(s, t) 0 F ind(s, t) = s.length F ind(s, t) s.lengtht.length

2. Your task Consider the code for find given in part 4. For this assignment, you are asked to 1. Write an invariant for the loop, which will be appropriate to prove correctness of find. You can either use the invariant given in part 3, or dene your own invariant. 2. Prove that the initialization code (lines 4-6) establishes the invariant. 3. Prove that the loop body re-establishes the invariant. 4. Prove that all array accesses are legal. 5. Prove that the invariant and termination imply the mid-condition.

2. An appropriate invariant You may use the following invaraint, if you like to. We enumerate the conjuncts of the invariant as follows: 1

(I1) (I2) (I3) (I4) (I5)

s s0 t t0 0 i s.length 0 j t.length i j M atch(s, t, i j, j) ij 1 < F ind(s, t) found j = t.length

4. The code and its specication


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

int find( char[] s, char[] t ) { // PRE: s = null = t // POST: r = F ind(s0 , t0 ) int i = 0; int j = 0; boolean found = t.length==0; // INV: ?? // VAR: ?? while ( j<t.length && i<s.length && !found ) { if ( s[i]==t[j] ){ i++; j++; if ( j==t.length ) { found = true; }; } else { i = i - j + 1; j = 0; }; }; // MID: (found F ind(s, t) = ij1) (!found F ind(s, t) = s.length) if ( found ) { return i-j ;} else { return s.length; } }

21 22 23 24 25 26

You might also like