Professional Documents
Culture Documents
Spec-141-4-0 (2) SDFHD
Spec-141-4-0 (2) SDFHD
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
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