id
stringlengths
3
3
name
stringlengths
3
3
docstring
stringlengths
18
18
code
stringlengths
129
20.6k
ground_truth
stringlengths
148
21.8k
test_file
stringlengths
15
119
000
000
Dafny program: 000
function sorted(a: array<int>) : bool reads a { forall i,j : int :: 0 <= i < j < a.Length ==> a[i] <= a[j] } method BinarySearch(a: array<int>, x: int) returns (index: int) requires sorted(a) ensures 0 <= index < a.Length ==> a[index] == x ensures index == -1 ==> forall i : int :: 0 <= i < a.Length ==> a[i] != x { var low := 0; var high := a.Length - 1; var mid := 0; while (low <= high) { mid := (high + low) / 2; if a[mid] < x { low := mid + 1; } else if a[mid] > x { high := mid - 1; } else { return mid; } } return -1; }
function sorted(a: array<int>) : bool reads a { forall i,j : int :: 0 <= i < j < a.Length ==> a[i] <= a[j] } method BinarySearch(a: array<int>, x: int) returns (index: int) requires sorted(a) ensures 0 <= index < a.Length ==> a[index] == x ensures index == -1 ==> forall i : int :: 0 <= i < a.Length ==> a[i] != x { var low := 0; var high := a.Length - 1; var mid := 0; while (low <= high) invariant 0 <= low <= high + 1 <= a.Length invariant x !in a[..low] && x !in a[high + 1..] { mid := (high + low) / 2; if a[mid] < x { low := mid + 1; } else if a[mid] > x { high := mid - 1; } else { return mid; } } return -1; }
630-dafny_tmp_tmpz2kokaiq_Solution.dfy
003
003
Dafny program: 003
// Noa Leron 207131871 // Tsuri Farhana 315016907 // definitions borrowed from Rustan Leino's Program Proofs Chapter 7 // (https://program-proofs.com/code.html example code in Dafny; source file 7-Unary.dfy) datatype Unary = Zero | Suc(pred: Unary) ghost function UnaryToNat(x: Unary): nat { match x case Zero => 0 case Suc(x') => 1 + UnaryToNat(x') } ghost function NatToUnary(n: nat): Unary { if n == 0 then Zero else Suc(NatToUnary(n-1)) } lemma NatUnaryCorrespondence(n: nat, x: Unary) ensures UnaryToNat(NatToUnary(n)) == n ensures NatToUnary(UnaryToNat(x)) == x { } predicate Less(x: Unary, y: Unary) { y != Zero && (x.Suc? ==> Less(x.pred, y.pred)) } predicate LessAlt(x: Unary, y: Unary) { y != Zero && (x == Zero || Less(x.pred, y.pred)) } lemma LessSame(x: Unary, y: Unary) ensures Less(x, y) == LessAlt(x, y) { } lemma LessCorrect(x: Unary, y: Unary) ensures Less(x, y) <==> UnaryToNat(x) < UnaryToNat(y) { } lemma LessTransitive(x: Unary, y: Unary, z: Unary) requires Less(x, y) && Less(y, z) ensures Less(x, z) { } function Add(x: Unary, y: Unary): Unary { match y case Zero => x case Suc(y') => Suc(Add(x, y')) } lemma {:induction false} SucAdd(x: Unary, y: Unary) ensures Suc(Add(x, y)) == Add(Suc(x), y) { match y case Zero => case Suc(y') => calc { Suc(Add(x, Suc(y'))); == // def. Add Suc(Suc(Add(x, y'))); == { SucAdd(x, y'); } Suc(Add(Suc(x), y')); == // def. Add Add(Suc(x), Suc(y')); } } lemma {:induction false} AddZero(x: Unary) ensures Add(Zero, x) == x { match x case Zero => case Suc(x') => calc { Add(Zero, Suc(x')); == // def. Add Suc(Add(Zero, x')); == { AddZero(x'); } Suc(x'); } } function Sub(x: Unary, y: Unary): Unary requires !Less(x, y) { match y case Zero => x case Suc(y') => Sub(x.pred, y') } function Mul(x: Unary, y: Unary): Unary { match x case Zero => Zero case Suc(x') => Add(Mul(x', y), y) } lemma SubStructurallySmaller(x: Unary, y: Unary) requires !Less(x, y) && y != Zero ensures Sub(x, y) < x { } lemma AddSub(x: Unary, y: Unary) requires !Less(x, y) ensures Add(Sub(x, y), y) == x { } /* Goal: implement correcly and clearly, using iterative code (no recursion), documenting the proof obligations as we've learned, with assertions and a lemma for each proof goal - DO NOT modify the specification or any of the definitions given in this file - Not all definitions above are relevant, some are simply included as examples - Feel free to use existing non-ghost functions/predicates in your code, and existing lemmas (for the proof) in your annotations - New functions/predicates may be added ONLY as ghost - If it helps you in any way, a recursive implementation + proof can be found in the book and the downloadable source file [https://program-proofs.com/code.html example code in Dafny, source file 7-Unary.dfy] */ method{:verify false} IterativeDivMod'(x: Unary, y: Unary) returns (d: Unary, m: Unary) requires y != Zero ensures Add(Mul(d, y), m) == x && Less(m, y) { if (Less(x, y)) { d := Zero; m := x; } else{ var x0: Unary := x; d := Zero; while (!Less(x0, y)) { d := Suc(d); x0 := Sub(x0, y); } m := x0; } } method IterativeDivMod(x: Unary, y: Unary) returns (d: Unary, m: Unary) requires y != Zero ensures Add(Mul(d, y), m) == x && Less(m, y) { if (Less(x, y)) { AddZero(x); d := Zero; m := x; } else{ var x0: Unary := x; d := Zero; AddZero(x); while (!Less(x0, y)) { AddMulSucSubEqAddMul(d, y , x0); d := Suc(d); SubStructurallySmaller(x0, y); x0 := Sub(x0, y); } m := x0; } } lemma AddMulEqMulSuc(a: Unary, b: Unary) ensures Mul(Suc(a), b) == Add(Mul(a, b), b) { calc{ Mul(Suc(a), b); == // def. Mul Add(Mul(a, b), b); } } lemma AddMulSucSubEqAddMul(d: Unary, y: Unary, x0: Unary) requires !Less(x0, y) requires y != Zero ensures Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0) { calc{ Add(Mul(Suc(d), y), Sub(x0, y)); == {AddMulEqMulSuc(d, y); Add(Add(Mul(d, y), y), Sub(x0, y)); == {AddTransitive(Mul(d, y), y, Sub(x0, y)); Add(Mul(d, y), Add(y, Sub(x0, y))); == {AddCommutative(Sub(x0, y), y); Add(Mul(d, y), Add(Sub(x0, y), y)); == {assert !Less(x0, y); AddSub(x0, y); Add(Mul(d, y), x0); } } lemma AddTransitive(a: Unary, b: Unary, c: Unary) ensures Add(a, Add(b, c)) == Add(Add(a, b), c) {//These assertions are only for documanting the proof obligations match c case Zero => calc{ Add(a, Add(b, c)); == Add(a, Add(b, Zero)); == // def. Add Add(a, b); == // def. Add Add(Add(a,b), Zero); == Add(Add(a,b), c); } case Suc(c') => match b case Zero => calc{ Add(a, Add(b, c)); == Add(a, Add(Zero, Suc(c'))); == {AddZero(Suc(c')); Add(a, Suc(c')); == // def. Add Add(Add(a, Zero), Suc(c')); == Add(Add(a, b), Suc(c')); == Add(Add(a,b), c); } case Suc(b') => match a case Zero => calc{ Add(a, Add(b, c)); == Add(Zero, Add(Suc(b'), Suc(c'))); == {AddZero(Add(Suc(b'), Suc(c'))); Add(Suc(b'), Suc(c')); == {AddZero(Suc(b')); Add(Add(Zero, Suc(b')), Suc(c')); == Add(Add(a, b), c); } case Suc(a') => calc{ Add(a, Add(b, c)); == Add(Suc(a'), Add(Suc(b'), Suc(c'))); == // def. Add Add(Suc(a'), Suc(Add(Suc(b'), c'))); == // def. Add Suc(Add(Suc(a'), Add(Suc(b'), c'))); == {SucAdd(a', Add(Suc(b'), c')); Suc(Suc(Add(a', Add(Suc(b'), c')))); == {SucAdd(b', c'); Suc(Suc(Add(a', Suc(Add(b', c'))))); == // def. Add Suc(Suc(Suc(Add(a', Add(b', c'))))); == {AddTransitive(a', b', c'); Suc(Suc(Suc(Add(Add(a',b'), c')))); == // def. Add Suc(Suc(Add(Add(a', b'), Suc(c')))); == {SucAdd(Add(a', b'), Suc(c')); Suc(Add(Suc(Add(a', b')), Suc(c'))); == {SucAdd(a', b'); Suc(Add(Add(Suc(a'), b'), Suc(c'))); == {SucAdd(Add(Suc(a'), b'), Suc(c')); Add(Suc(Add(Suc(a'), b')), Suc(c')); == // def. Add Add(Add(Suc(a'), Suc(b')), Suc(c')); == Add(Add(a,b), c); } } lemma AddCommutative(a: Unary, b: Unary) ensures Add(a, b) == Add(b, a) { match b case Zero => calc{ Add(a, b); == Add(a, Zero); == // def. Add a; == {AddZero(a); Add(Zero, a); == Add(b, a); } case Suc(b') => calc{ Add(a, b); == Add(a, Suc(b')); == // def. Add Suc(Add(a, b')); == {AddCommutative(a, b'); Suc(Add(b', a)); == {SucAdd(b', a); Add(Suc(b'), a); == Add(b, a); } } method Main() { var U3 := Suc(Suc(Suc(Zero))); var U7 := Suc(Suc(Suc(Suc(U3)))); var d, m := IterativeDivMod(U7, U3); print "Just as 7 divided by 3 is 2 with a remainder of 1, IterativeDivMod(", U7, ", ", U3, ") is ", d, " with a remainder of ", m; }
// Noa Leron 207131871 // Tsuri Farhana 315016907 // definitions borrowed from Rustan Leino's Program Proofs Chapter 7 // (https://program-proofs.com/code.html example code in Dafny; source file 7-Unary.dfy) datatype Unary = Zero | Suc(pred: Unary) ghost function UnaryToNat(x: Unary): nat { match x case Zero => 0 case Suc(x') => 1 + UnaryToNat(x') } ghost function NatToUnary(n: nat): Unary { if n == 0 then Zero else Suc(NatToUnary(n-1)) } lemma NatUnaryCorrespondence(n: nat, x: Unary) ensures UnaryToNat(NatToUnary(n)) == n ensures NatToUnary(UnaryToNat(x)) == x { } predicate Less(x: Unary, y: Unary) { y != Zero && (x.Suc? ==> Less(x.pred, y.pred)) } predicate LessAlt(x: Unary, y: Unary) { y != Zero && (x == Zero || Less(x.pred, y.pred)) } lemma LessSame(x: Unary, y: Unary) ensures Less(x, y) == LessAlt(x, y) { } lemma LessCorrect(x: Unary, y: Unary) ensures Less(x, y) <==> UnaryToNat(x) < UnaryToNat(y) { } lemma LessTransitive(x: Unary, y: Unary, z: Unary) requires Less(x, y) && Less(y, z) ensures Less(x, z) { } function Add(x: Unary, y: Unary): Unary { match y case Zero => x case Suc(y') => Suc(Add(x, y')) } lemma {:induction false} SucAdd(x: Unary, y: Unary) ensures Suc(Add(x, y)) == Add(Suc(x), y) { match y case Zero => case Suc(y') => calc { Suc(Add(x, Suc(y'))); == // def. Add Suc(Suc(Add(x, y'))); == { SucAdd(x, y'); } Suc(Add(Suc(x), y')); == // def. Add Add(Suc(x), Suc(y')); } } lemma {:induction false} AddZero(x: Unary) ensures Add(Zero, x) == x { match x case Zero => case Suc(x') => calc { Add(Zero, Suc(x')); == // def. Add Suc(Add(Zero, x')); == { AddZero(x'); } Suc(x'); } } function Sub(x: Unary, y: Unary): Unary requires !Less(x, y) { match y case Zero => x case Suc(y') => Sub(x.pred, y') } function Mul(x: Unary, y: Unary): Unary { match x case Zero => Zero case Suc(x') => Add(Mul(x', y), y) } lemma SubStructurallySmaller(x: Unary, y: Unary) requires !Less(x, y) && y != Zero ensures Sub(x, y) < x { } lemma AddSub(x: Unary, y: Unary) requires !Less(x, y) ensures Add(Sub(x, y), y) == x { } /* Goal: implement correcly and clearly, using iterative code (no recursion), documenting the proof obligations as we've learned, with assertions and a lemma for each proof goal - DO NOT modify the specification or any of the definitions given in this file - Not all definitions above are relevant, some are simply included as examples - Feel free to use existing non-ghost functions/predicates in your code, and existing lemmas (for the proof) in your annotations - New functions/predicates may be added ONLY as ghost - If it helps you in any way, a recursive implementation + proof can be found in the book and the downloadable source file [https://program-proofs.com/code.html example code in Dafny, source file 7-Unary.dfy] */ method{:verify false} IterativeDivMod'(x: Unary, y: Unary) returns (d: Unary, m: Unary) requires y != Zero ensures Add(Mul(d, y), m) == x && Less(m, y) { if (Less(x, y)) { d := Zero; m := x; } else{ var x0: Unary := x; d := Zero; while (!Less(x0, y)) invariant Add(Mul(d, y), x0) == x decreases x0 { d := Suc(d); x0 := Sub(x0, y); } m := x0; } } method IterativeDivMod(x: Unary, y: Unary) returns (d: Unary, m: Unary) requires y != Zero ensures Add(Mul(d, y), m) == x && Less(m, y) { if (Less(x, y)) { assert Less(x, y); AddZero(x); assert Add(Zero, x) == x; assert Mul(Zero, y) == Zero; assert Add(Mul(Zero, y), x) == x; d := Zero; m := x; assert Add(Mul(d, y), m) == m; assert Less(m, y); assert Add(Mul(d, y), m) == x && Less(m, y); } else{ assert !Less(x, y); assert y != Zero; var x0: Unary := x; assert Mul(Zero, y) == Zero; d := Zero; assert Mul(d, y) == Zero; AddZero(x); assert Add(Zero, x) == x; assert Add(Mul(d, y), x) == x; assert Add(Mul(d, y), x0) == x; while (!Less(x0, y)) invariant Add(Mul(d, y), x0) == x decreases x0 { assert Add(Mul(d, y), x0) == x; assert !Less(x0, y); assert y != Zero; AddMulSucSubEqAddMul(d, y , x0); assert Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0); assert Add(Mul(Suc(d), y), Sub(x0, y)) == x; d := Suc(d); assert !Less(x0, y) && y != Zero; SubStructurallySmaller(x0, y); assert Sub(x0, y) < x0; // decreases x0 := Sub(x0, y); assert Add(Mul(d, y), x0) == x; } assert Add(Mul(d, y), x0) == x; m := x0; assert Add(Mul(d, y), m) == x; } assert Add(Mul(d, y), m) == x; } lemma AddMulEqMulSuc(a: Unary, b: Unary) ensures Mul(Suc(a), b) == Add(Mul(a, b), b) { calc{ Mul(Suc(a), b); == // def. Mul Add(Mul(a, b), b); } } lemma AddMulSucSubEqAddMul(d: Unary, y: Unary, x0: Unary) requires !Less(x0, y) requires y != Zero ensures Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0) { calc{ Add(Mul(Suc(d), y), Sub(x0, y)); == {AddMulEqMulSuc(d, y); assert Mul(Suc(d), y) == Add(Mul(d, y), y);} Add(Add(Mul(d, y), y), Sub(x0, y)); == {AddTransitive(Mul(d, y), y, Sub(x0, y)); assert Add(Mul(d, y), Add(y, Sub(x0, y))) == Add(Add(Mul(d, y), y), Sub(x0, y));} Add(Mul(d, y), Add(y, Sub(x0, y))); == {AddCommutative(Sub(x0, y), y); assert Add(Sub(x0, y), y) == Add(y, Sub(x0, y));} Add(Mul(d, y), Add(Sub(x0, y), y)); == {assert !Less(x0, y); AddSub(x0, y); assert Add(Sub(x0, y), y) == x0;} Add(Mul(d, y), x0); } } lemma AddTransitive(a: Unary, b: Unary, c: Unary) ensures Add(a, Add(b, c)) == Add(Add(a, b), c) {//These assertions are only for documanting the proof obligations match c case Zero => calc{ Add(a, Add(b, c)); == Add(a, Add(b, Zero)); == // def. Add Add(a, b); == // def. Add Add(Add(a,b), Zero); == Add(Add(a,b), c); } case Suc(c') => match b case Zero => calc{ Add(a, Add(b, c)); == Add(a, Add(Zero, Suc(c'))); == {AddZero(Suc(c')); assert Add(Zero, Suc(c')) == Suc(c');} Add(a, Suc(c')); == // def. Add Add(Add(a, Zero), Suc(c')); == Add(Add(a, b), Suc(c')); == Add(Add(a,b), c); } case Suc(b') => match a case Zero => calc{ Add(a, Add(b, c)); == Add(Zero, Add(Suc(b'), Suc(c'))); == {AddZero(Add(Suc(b'), Suc(c'))); assert Add(Zero, Add(Suc(b'), Suc(c'))) == Add(Suc(b'), Suc(c'));} Add(Suc(b'), Suc(c')); == {AddZero(Suc(b')); assert Add(Zero , Suc(b')) == Suc(b');} Add(Add(Zero, Suc(b')), Suc(c')); == Add(Add(a, b), c); } case Suc(a') => calc{ Add(a, Add(b, c)); == Add(Suc(a'), Add(Suc(b'), Suc(c'))); == // def. Add Add(Suc(a'), Suc(Add(Suc(b'), c'))); == // def. Add Suc(Add(Suc(a'), Add(Suc(b'), c'))); == {SucAdd(a', Add(Suc(b'), c')); assert Suc(Add(a', Add(Suc(b'), c'))) == Add(Suc(a'), Add(Suc(b'), c'));} Suc(Suc(Add(a', Add(Suc(b'), c')))); == {SucAdd(b', c'); assert Suc(Add(b', c')) == Add(Suc(b'), c');} Suc(Suc(Add(a', Suc(Add(b', c'))))); == // def. Add Suc(Suc(Suc(Add(a', Add(b', c'))))); == {AddTransitive(a', b', c'); assert Add(a', Add(b',c')) == Add(Add(a',b'),c');} Suc(Suc(Suc(Add(Add(a',b'), c')))); == // def. Add Suc(Suc(Add(Add(a', b'), Suc(c')))); == {SucAdd(Add(a', b'), Suc(c')); assert Suc(Add(Add(a', b'), Suc(c'))) == Add(Suc(Add(a', b')), Suc(c'));} Suc(Add(Suc(Add(a', b')), Suc(c'))); == {SucAdd(a', b'); assert Suc(Add(a', b')) == Add(Suc(a'), b');} Suc(Add(Add(Suc(a'), b'), Suc(c'))); == {SucAdd(Add(Suc(a'), b'), Suc(c')); assert Suc(Add(Add(Suc(a'), b'), Suc(c'))) == Add(Suc(Add(Suc(a'), b')), Suc(c'));} Add(Suc(Add(Suc(a'), b')), Suc(c')); == // def. Add Add(Add(Suc(a'), Suc(b')), Suc(c')); == Add(Add(a,b), c); } } lemma AddCommutative(a: Unary, b: Unary) ensures Add(a, b) == Add(b, a) { match b case Zero => calc{ Add(a, b); == Add(a, Zero); == // def. Add a; == {AddZero(a); assert Add(Zero, a) == a;} Add(Zero, a); == Add(b, a); } case Suc(b') => calc{ Add(a, b); == Add(a, Suc(b')); == // def. Add Suc(Add(a, b')); == {AddCommutative(a, b'); assert Add(a, b') == Add(b', a);} Suc(Add(b', a)); == {SucAdd(b', a); assert Suc(Add(b',a)) == Add(Suc(b'),a);} Add(Suc(b'), a); == Add(b, a); } } method Main() { var U3 := Suc(Suc(Suc(Zero))); assert UnaryToNat(U3) == 3; var U7 := Suc(Suc(Suc(Suc(U3)))); assert UnaryToNat(U7) == 7; var d, m := IterativeDivMod(U7, U3); assert Add(Mul(d, U3), m) == U7 && Less(m, U3); print "Just as 7 divided by 3 is 2 with a remainder of 1, IterativeDivMod(", U7, ", ", U3, ") is ", d, " with a remainder of ", m; }
AssertivePrograming_tmp_tmpwf43uz0e_DivMode_Unary.dfy
004
004
Dafny program: 004
// Noa Leron 207131871 // Tsuri Farhana 315016907 ghost predicate ExistsSubstring(str1: string, str2: string) { // string in Dafny is a sequence of characters (seq<char>) and <= on sequences is the prefix relation exists offset :: 0 <= offset <= |str1| && str2 <= str1[offset..] } ghost predicate Post(str1: string, str2: string, found: bool, i: nat) { (found <==> ExistsSubstring(str1, str2)) && (found ==> i + |str2| <= |str1| && str2 <= str1[i..]) } /* Goal: Verify correctness of the following code. Once done, remove the {:verify false} (or turn it into {:verify true}). Feel free to add GHOST code, including calls to lemmas. But DO NOT modify the specification or the original (executable) code. */ method {:verify true} FindFirstOccurrence(str1: string, str2: string) returns (found: bool, i: nat) ensures Post(str1, str2, found, i) { if |str2| == 0 { found, i := true, 0; } else if |str1| < |str2| { found, i := false, 0; // value of i irrelevant in this case } else { found, i := false, |str2|-1; while !found && i < |str1| { var j := |str2|-1; ghost var old_i := i; ghost var old_j := j; while !found && str1[i] == str2[j] { if j == 0 { found := true; } else { i, j := i-1, j-1; } } if !found { Lemma1(str1, str2, i, j, old_i, old_j, found); // ==> i := i+|str2|-j; } } } } method Main() { var str1a, str1b := "string", " in Dafny is a sequence of characters (seq<char>)"; var str1, str2 := str1a + str1b, "ring"; var found, i := FindFirstOccurrence(str1, str2); var offset := 2; } } } print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found; if found { print " and i == ", i; } str1 := "<= on sequences is the prefix relation"; found, i := FindFirstOccurrence(str1, str2); print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found; if found { print " and i == ", i; } } //this is our lemmas, invatiants and presicats ghost predicate Outter_Inv_correctness(str1: string, str2: string, found: bool, i : nat) { (found ==> (i + |str2| <= |str1| && str2 <= str1[i..])) // Second part of post condition && (!found && 0 < i <= |str1| && i != |str2|-1 ==> !(ExistsSubstring(str1[..i], str2))) // First part of post condition && (!found ==> i <= |str1|) } ghost predicate Inner_Inv_correctness(str1: string, str2: string, i : nat, j: int, found: bool){ 0 <= j <= i && // index in range j < |str2| && // index in range i < |str1| &&// index in range (str1[i] == str2[j] ==> str2[j..] <= str1[i..]) && (found ==> j==0 && str1[i] == str2[j]) } ghost predicate Inner_Inv_Termination(str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat){ old_j - j == old_i - i } lemma {:verify true} Lemma1 (str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat, found: bool) // requires old_j - j == old_i - i; requires !found; requires |str2| > 0; requires Outter_Inv_correctness(str1, str2, found, old_i); requires i+|str2|-j == old_i + 1; requires old_i+1 >= |str2|; requires old_i+1 <= |str1|; requires 0 <= i < |str1| && 0 <= j < |str2|; requires str1[i] != str2[j]; requires |str2| > 0; requires 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2)); ensures 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2)); { calc{ 0 < old_i+1 <= |str1| && (ExistsSubstring(str1[..old_i+1], str2)) && !(str2 <= str1[old_i+1 - |str2|..old_i+1]); ==> (!(ExistsSubstring(str1[..old_i], str2))) && (ExistsSubstring(str1[..old_i+1], str2)) && !(str2 <= str1[old_i+1 - |str2|..old_i+1]); ==> {Lemma2(str1, str2, old_i, found);} ((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> (|str1[old_i+1 - |str2|..old_i+1]| == |str2|) && (str2 <= str1[old_i+1 - |str2| .. old_i+1])) && !(str2 <= str1[old_i+1 - |str2|..old_i+1]); ==> ((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> false); } } lemma {:verify true} Lemma2 (str1: string, str2: string, i : nat, found: bool) requires 0 <= i < |str1|; requires 0 < |str2| <= i+1; requires !ExistsSubstring(str1[..i], str2); requires ExistsSubstring(str1[..i+1], str2); ensures str2 <= str1[i+1 - |str2| .. i+1]; { && ((offset <= i) || (offset == i+1)); calc{ (0 < |str2|) && (!exists offset :: 0 <= offset <= i && str2 <= str1[offset..i]) && (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]); ==> (0 < |str2|) && (forall offset :: 0 <= offset <= i ==> !(str2 <= str1[offset..i])) && (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1]) && (forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]))); ==> {Lemma3(str1, str2, i);} (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i]))); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0)); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0) && (offset != i+1)); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])) && (offset <= i)); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && !(str2 <= str1[offset..i])); ==> str2 <= str1[i+1 - |str2| .. i+1]; } } lemma Lemma3(str1: string, str2: string, i : nat) requires 0 <= i < |str1|; requires 0 < |str2| <= i+1; requires exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1]; requires forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i])); ensures exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])); { var offset :| (0 <= offset <= i+1) && str2 <= str1[offset..i+1]; }
// Noa Leron 207131871 // Tsuri Farhana 315016907 ghost predicate ExistsSubstring(str1: string, str2: string) { // string in Dafny is a sequence of characters (seq<char>) and <= on sequences is the prefix relation exists offset :: 0 <= offset <= |str1| && str2 <= str1[offset..] } ghost predicate Post(str1: string, str2: string, found: bool, i: nat) { (found <==> ExistsSubstring(str1, str2)) && (found ==> i + |str2| <= |str1| && str2 <= str1[i..]) } /* Goal: Verify correctness of the following code. Once done, remove the {:verify false} (or turn it into {:verify true}). Feel free to add GHOST code, including calls to lemmas. But DO NOT modify the specification or the original (executable) code. */ method {:verify true} FindFirstOccurrence(str1: string, str2: string) returns (found: bool, i: nat) ensures Post(str1, str2, found, i) { if |str2| == 0 { found, i := true, 0; assert Post(str1, str2, found, i); // this case is easy for dafny :) } else if |str1| < |str2| { found, i := false, 0; // value of i irrelevant in this case assert Post(str1, str2, found, i); // this case is easy for dafny :) } else { found, i := false, |str2|-1; assert |str2| > 0; assert |str1| >= |str2|; assert Outter_Inv_correctness(str1, str2, false, |str2|-1); while !found && i < |str1| invariant Outter_Inv_correctness(str1, str2, found, i); decreases if !found then 1 else 0, |str1| - i; { assert Outter_Inv_correctness(str1, str2, found, i); assert |str2| > 0; assert !found && i < |str1|; var j := |str2|-1; ghost var old_i := i; ghost var old_j := j; while !found && str1[i] == str2[j] invariant Inner_Inv_Termination(str1, str2, i, j, old_i, old_j); invariant Inner_Inv_correctness (str1, str2, i, j, found); decreases j, if !found then 1 else 0; { if j == 0 { assert j==0 && str1[i] == str2[j]; found := true; assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j); assert Inner_Inv_correctness(str1, str2, i, j, found); } else { assert j > 0; assert Inner_Inv_Termination(str1, str2, i-1, j-1, old_i, old_j); assert Inner_Inv_correctness(str1, str2, i-1, j-1, found); i, j := i-1, j-1; assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j); assert Inner_Inv_correctness(str1, str2, i, j, found); } assert j >= 0; assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j); assert Inner_Inv_correctness(str1, str2, i, j, found); } assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j); assert Inner_Inv_correctness(str1, str2, i, j, found); assert found || str1[i] != str2[j]; // gaurd negation assert found ==> i + |str2| <= |str1| && str2 <= str1[i..]; assert !found ==> str1[i] != str2[j]; if !found { assert i < |str1|; assert |str2| > 0; assert old_j - j == old_i - i; assert old_i < i+|str2|-j; assert Outter_Inv_correctness(str1, str2, found, old_i); assert i+|str2|-j == old_i + 1; assert str1[i] != str2[j]; assert |str1[old_i+1 - |str2|..old_i+1]| == |str2|; assert str1[old_i+1 - |str2|..old_i+1] != str2; assert 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2)); Lemma1(str1, str2, i, j, old_i, old_j, found); // ==> assert 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2)); assert 0 < i+|str2|-j <= |str1| ==> !(ExistsSubstring(str1[..i+|str2|-j], str2)); assert Outter_Inv_correctness(str1, str2, found, i+|str2|-j); i := i+|str2|-j; assert old_i < i; assert Outter_Inv_correctness(str1, str2, found, i); assert i <= |str1|; } assert !found ==> i <= |str1|; assert !found ==> old_i < i; assert !found ==> Outter_Inv_correctness(str1, str2, found, i); assert found ==> Outter_Inv_correctness(str1, str2, found, i); assert Outter_Inv_correctness(str1, str2, found, i); } assert Outter_Inv_correctness(str1, str2, found, i); assert (found ==> i + |str2| <= |str1| && str2 <= str1[i..]); assert (!found && 0 < i <= |str1| ==> !(ExistsSubstring(str1[..i], str2))); assert (!found ==> i <= |str1|); assert found || i >= |str1|; // gaurd negation assert (!found && i == |str1| ==> !(ExistsSubstring(str1[..i], str2))); assert i == |str1| ==> str1[..i] == str1; assert (!found && i == |str1| ==> !(ExistsSubstring(str1, str2))); assert !found ==> i >= |str1|; assert !found ==> i == |str1|; assert (!found ==> !ExistsSubstring(str1, str2)); assert (found ==> ExistsSubstring(str1, str2)); assert (found <==> ExistsSubstring(str1, str2)); assert (found ==> i + |str2| <= |str1| && str2 <= str1[i..]); assert Post(str1, str2, found, i); } assert Post(str1, str2, found, i); } method Main() { var str1a, str1b := "string", " in Dafny is a sequence of characters (seq<char>)"; var str1, str2 := str1a + str1b, "ring"; var found, i := FindFirstOccurrence(str1, str2); assert found by { assert ExistsSubstring(str1, str2) by { var offset := 2; assert 0 <= offset <= |str1|; assert str2 <= str1[offset..] by { assert str2 == str1[offset..][..4]; } } } print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found; if found { print " and i == ", i; } str1 := "<= on sequences is the prefix relation"; found, i := FindFirstOccurrence(str1, str2); print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found; if found { print " and i == ", i; } } //this is our lemmas, invatiants and presicats ghost predicate Outter_Inv_correctness(str1: string, str2: string, found: bool, i : nat) { (found ==> (i + |str2| <= |str1| && str2 <= str1[i..])) // Second part of post condition && (!found && 0 < i <= |str1| && i != |str2|-1 ==> !(ExistsSubstring(str1[..i], str2))) // First part of post condition && (!found ==> i <= |str1|) } ghost predicate Inner_Inv_correctness(str1: string, str2: string, i : nat, j: int, found: bool){ 0 <= j <= i && // index in range j < |str2| && // index in range i < |str1| &&// index in range (str1[i] == str2[j] ==> str2[j..] <= str1[i..]) && (found ==> j==0 && str1[i] == str2[j]) } ghost predicate Inner_Inv_Termination(str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat){ old_j - j == old_i - i } lemma {:verify true} Lemma1 (str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat, found: bool) // requires old_j - j == old_i - i; requires !found; requires |str2| > 0; requires Outter_Inv_correctness(str1, str2, found, old_i); requires i+|str2|-j == old_i + 1; requires old_i+1 >= |str2|; requires old_i+1 <= |str1|; requires 0 <= i < |str1| && 0 <= j < |str2|; requires str1[i] != str2[j]; requires |str2| > 0; requires 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2)); ensures 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2)); { assert |str1[old_i+1 - |str2|..old_i+1]| == |str2|; assert str1[old_i+1 - |str2|..old_i+1] != str2; assert !(str2 <= str1[old_i+1 - |str2|..old_i+1]); assert 0 <= old_i < old_i+1 <= |str1|; assert old_i+1 >= |str2|; calc{ 0 < old_i+1 <= |str1| && (ExistsSubstring(str1[..old_i+1], str2)) && !(str2 <= str1[old_i+1 - |str2|..old_i+1]); ==> (!(ExistsSubstring(str1[..old_i], str2))) && (ExistsSubstring(str1[..old_i+1], str2)) && !(str2 <= str1[old_i+1 - |str2|..old_i+1]); ==> {Lemma2(str1, str2, old_i, found);} ((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> (|str1[old_i+1 - |str2|..old_i+1]| == |str2|) && (str2 <= str1[old_i+1 - |str2| .. old_i+1])) && !(str2 <= str1[old_i+1 - |str2|..old_i+1]); ==> ((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> false); } } lemma {:verify true} Lemma2 (str1: string, str2: string, i : nat, found: bool) requires 0 <= i < |str1|; requires 0 < |str2| <= i+1; requires !ExistsSubstring(str1[..i], str2); requires ExistsSubstring(str1[..i+1], str2); ensures str2 <= str1[i+1 - |str2| .. i+1]; { assert exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1] && ((offset <= i) || (offset == i+1)); calc{ (0 < |str2|) && (!exists offset :: 0 <= offset <= i && str2 <= str1[offset..i]) && (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]); ==> (0 < |str2|) && (forall offset :: 0 <= offset <= i ==> !(str2 <= str1[offset..i])) && (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1]) && (forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]))); ==> {Lemma3(str1, str2, i);} (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i]))); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0)); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0) && (offset != i+1)); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])) && (offset <= i)); ==> (0 < |str2|) && (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && !(str2 <= str1[offset..i])); ==> str2 <= str1[i+1 - |str2| .. i+1]; } } lemma Lemma3(str1: string, str2: string, i : nat) requires 0 <= i < |str1|; requires 0 < |str2| <= i+1; requires exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1]; requires forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i])); ensures exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])); { var offset :| (0 <= offset <= i+1) && str2 <= str1[offset..i+1]; assert 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i])); }
AssertivePrograming_tmp_tmpwf43uz0e_Find_Substring.dfy
005
005
Dafny program: 005
// Noa Leron 207131871 // Tsuri Farhana 315016907 predicate Sorted(q: seq<int>) { forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j] } /* Goal: Implement the well known merge sort algorithm in O(a.Length X log_2(a.Length)) time, recursively. - Divide the contents of the original array into two local arrays - After sorting the local arrays (recursively), merge the contents of the two returned arrays using the Merge method (see below) - DO NOT modify the specification or any other part of the method's signature - DO NOT introduce any further methods */ method MergeSort(a: array<int>) returns (b: array<int>) ensures b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..]) { if (a.Length <= 1) {b := a;} else{ var mid: nat := a.Length / 2; var a1: array<int> := new int[mid]; var a2: array<int> := new int[a.Length - mid]; var i: nat := 0; while (i < a1.Length ) { a1[i] := a[i]; a2[i] := a[i+mid]; i:=i+1; } if(a1.Length < a2.Length) { a2[i] := a[i+mid]; } // If a.Length is odd. else{ } a1:= MergeSort(a1); a2:= MergeSort(a2); b := new int [a.Length]; Merge(b, a1, a2); } } ghost predicate Inv(a: seq<int>, a1: seq<int>, a2: seq<int>, i: nat, mid: nat){ (i <= |a1|) && (i <= |a2|) && (i+mid <= |a|) && (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]) } /* Goal: Implement iteratively, correctly, efficiently, clearly DO NOT modify the specification or any other part of the method's signature */ method Merge(b: array<int>, c: array<int>, d: array<int>) requires b != c && b != d && b.Length == c.Length + d.Length requires Sorted(c[..]) && Sorted(d[..]) ensures Sorted(b[..]) && multiset(b[..]) == multiset(c[..])+multiset(d[..]) modifies b { var i: nat, j: nat := 0, 0; while i + j < b.Length { i,j := MergeLoop (b,c,d,i,j); } LemmaMultysetsEquals(b[..],c[..],d[..],i,j); } //This is a method that replace the loop body method {:verify true} MergeLoop(b: array<int>, c: array<int>, d: array<int>,i0: nat , j0: nat) returns (i: nat, j: nat) requires b != c && b != d && b.Length == c.Length + d.Length requires Sorted(c[..]) && Sorted(d[..]) requires i0 <= c.Length && j0 <= d.Length && i0 + j0 <= b.Length requires InvSubSet(b[..],c[..],d[..],i0,j0) requires InvSorted(b[..],c[..],d[..],i0,j0) requires i0 + j0 < b.Length modifies b ensures i <= c.Length && j <= d.Length && i + j <= b.Length ensures InvSubSet(b[..],c[..],d[..],i,j) ensures InvSorted(b[..],c[..],d[..],i,j) //decreases ensures ensures 0 <= c.Length - i < c.Length - i0 || (c.Length - i == c.Length - i0 && 0 <= d.Length - j < d.Length - j0) { i,j := i0,j0; if(i == c.Length || (j< d.Length && d[j] < c[i])){ // in this case we take the next value from d b[i+j] := d[j]; lemmaInvSubsetTakeValueFromD(b[..],c[..],d[..],i,j); j := j + 1; } else{ // in this case we take the next value from c b[i+j] := c[i]; lemmaInvSubsetTakeValueFromC(b[..],c[..],d[..],i,j); i := i + 1; } } //Loop invariant - b is sprted so far and the next two potential values that will go into b are bigger then the biggest value in b. ghost predicate InvSorted(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){ i <= |c| && j <= |d| && i + j <= |b| && ((i+j > 0 && i < |c|) ==> (b[j + i - 1] <= c[i])) && ((i+j > 0 && j < |d|) ==> (b[j + i - 1] <= d[j])) && Sorted(b[..i+j]) } //Loop invariant - the multiset of the prefix of b so far is the same multiset as the prefixes of c and d so far. ghost predicate InvSubSet(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){ i <= |c| && j <= |d| && i + j <= |b| && multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) } //This lemma helps dafny see that if the prefixs of arrays are the same multiset until the end of the arrays, //all the arrays are the same multiset. lemma LemmaMultysetsEquals (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat) requires i == |c|; requires j == |d|; requires i + j == |b|; requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) ensures multiset(b[..]) == multiset(c[..])+multiset(d[..]); { } //This lemma helps dafny see that after adding the next value from c to b the prefixes are still the same subsets. lemma lemmaInvSubsetTakeValueFromC (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat) requires i < |c|; requires j <= |d|; requires i + j < |b|; requires |c| + |d| == |b|; requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) requires b[i+j] == c[i] ensures multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j]) { } //This lemma helps dafny see that after adding the next value from d to b the prefixes are still the same subsets. lemma{:verify true} lemmaInvSubsetTakeValueFromD (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat) requires i <= |c|; requires j < |d|; requires i + j < |b|; requires |c| + |d| == |b|; requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) requires b[i+j] == d[j] ensures multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1]) { } method Main() { var a := new int[3] [4, 8, 6]; var q0 := a[..]; a := MergeSort(a); print "\nThe sorted version of ", q0, " is ", a[..]; a := new int[5] [3, 8, 5, -1, 10]; q0 := a[..]; a := MergeSort(a); print "\nThe sorted version of ", q0, " is ", a[..]; //assert a[..] == [-1, 3, 5, 8, 10]; }
// Noa Leron 207131871 // Tsuri Farhana 315016907 predicate Sorted(q: seq<int>) { forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j] } /* Goal: Implement the well known merge sort algorithm in O(a.Length X log_2(a.Length)) time, recursively. - Divide the contents of the original array into two local arrays - After sorting the local arrays (recursively), merge the contents of the two returned arrays using the Merge method (see below) - DO NOT modify the specification or any other part of the method's signature - DO NOT introduce any further methods */ method MergeSort(a: array<int>) returns (b: array<int>) ensures b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..]) decreases a.Length { if (a.Length <= 1) {b := a;} else{ var mid: nat := a.Length / 2; var a1: array<int> := new int[mid]; var a2: array<int> := new int[a.Length - mid]; assert a1.Length <= a2.Length; assert a.Length == a1.Length + a2.Length; var i: nat := 0; while (i < a1.Length ) invariant Inv(a[..], a1[..], a2[..], i, mid) decreases a1.Length - i { a1[i] := a[i]; a2[i] := a[i+mid]; i:=i+1; } assert !(i < a1.Length); assert (i >= a1.Length); assert i == a1.Length; assert Inv(a[..], a1[..], a2[..], i, mid); assert (i <= |a1[..]|) && (i <= |a2[..]|) && (i+mid <= |a[..]|); assert (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]); if(a1.Length < a2.Length) { a2[i] := a[i+mid]; assert i+1 == a2.Length; assert (a2[..i+1] == a[mid..(i+1+mid)]); assert (a1[..i] == a[..i]) && (a2[..i+1] == a[mid..(i+1+mid)]); assert a[..i] + a[i..i+1+mid] == a1[..i] + a2[..i+1]; assert a[..i] + a[i..i+1+mid] == a1[..] + a2[..]; assert a[..] == a1[..] + a2[..]; } // If a.Length is odd. else{ assert i == a2.Length; assert (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]); assert a[..i] + a[i..i+mid] == a1[..i] + a2[..i]; assert a[..i] + a[i..i+mid] == a1[..] + a2[..]; assert a[..] == a1[..] + a2[..]; } assert a1.Length < a.Length; a1:= MergeSort(a1); assert a2.Length < a.Length; a2:= MergeSort(a2); b := new int [a.Length]; Merge(b, a1, a2); assert multiset(b[..]) == multiset(a1[..]) + multiset(a2[..]); assert Sorted(b[..]); } assert b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..]); } ghost predicate Inv(a: seq<int>, a1: seq<int>, a2: seq<int>, i: nat, mid: nat){ (i <= |a1|) && (i <= |a2|) && (i+mid <= |a|) && (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]) } /* Goal: Implement iteratively, correctly, efficiently, clearly DO NOT modify the specification or any other part of the method's signature */ method Merge(b: array<int>, c: array<int>, d: array<int>) requires b != c && b != d && b.Length == c.Length + d.Length requires Sorted(c[..]) && Sorted(d[..]) ensures Sorted(b[..]) && multiset(b[..]) == multiset(c[..])+multiset(d[..]) modifies b { var i: nat, j: nat := 0, 0; while i + j < b.Length invariant i <= c.Length && j <= d.Length && i + j <= b.Length invariant InvSubSet(b[..],c[..],d[..],i,j) invariant InvSorted(b[..],c[..],d[..],i,j) decreases c.Length-i, d.Length-j { i,j := MergeLoop (b,c,d,i,j); assert InvSubSet(b[..],c[..],d[..],i,j); assert InvSorted(b[..],c[..],d[..],i,j); } assert InvSubSet(b[..],c[..],d[..],i,j); LemmaMultysetsEquals(b[..],c[..],d[..],i,j); assert multiset(b[..]) == multiset(c[..])+multiset(d[..]); } //This is a method that replace the loop body method {:verify true} MergeLoop(b: array<int>, c: array<int>, d: array<int>,i0: nat , j0: nat) returns (i: nat, j: nat) requires b != c && b != d && b.Length == c.Length + d.Length requires Sorted(c[..]) && Sorted(d[..]) requires i0 <= c.Length && j0 <= d.Length && i0 + j0 <= b.Length requires InvSubSet(b[..],c[..],d[..],i0,j0) requires InvSorted(b[..],c[..],d[..],i0,j0) requires i0 + j0 < b.Length modifies b ensures i <= c.Length && j <= d.Length && i + j <= b.Length ensures InvSubSet(b[..],c[..],d[..],i,j) ensures InvSorted(b[..],c[..],d[..],i,j) //decreases ensures ensures 0 <= c.Length - i < c.Length - i0 || (c.Length - i == c.Length - i0 && 0 <= d.Length - j < d.Length - j0) { i,j := i0,j0; if(i == c.Length || (j< d.Length && d[j] < c[i])){ // in this case we take the next value from d assert InvSorted(b[..][i+j:=d[j]],c[..],d[..],i,j+1); b[i+j] := d[j]; lemmaInvSubsetTakeValueFromD(b[..],c[..],d[..],i,j); assert InvSubSet(b[..],c[..],d[..],i,j+1); assert InvSorted(b[..],c[..],d[..],i,j+1); j := j + 1; } else{ assert j == d.Length || (i < c.Length && c[i] <= d[j]); // in this case we take the next value from c assert InvSorted(b[..][i+j:=c[i]],c[..],d[..],i+1,j); b[i+j] := c[i]; lemmaInvSubsetTakeValueFromC(b[..],c[..],d[..],i,j); assert InvSubSet(b[..],c[..],d[..],i+1,j); assert InvSorted(b[..],c[..],d[..],i+1,j); i := i + 1; } } //Loop invariant - b is sprted so far and the next two potential values that will go into b are bigger then the biggest value in b. ghost predicate InvSorted(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){ i <= |c| && j <= |d| && i + j <= |b| && ((i+j > 0 && i < |c|) ==> (b[j + i - 1] <= c[i])) && ((i+j > 0 && j < |d|) ==> (b[j + i - 1] <= d[j])) && Sorted(b[..i+j]) } //Loop invariant - the multiset of the prefix of b so far is the same multiset as the prefixes of c and d so far. ghost predicate InvSubSet(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){ i <= |c| && j <= |d| && i + j <= |b| && multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) } //This lemma helps dafny see that if the prefixs of arrays are the same multiset until the end of the arrays, //all the arrays are the same multiset. lemma LemmaMultysetsEquals (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat) requires i == |c|; requires j == |d|; requires i + j == |b|; requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) ensures multiset(b[..]) == multiset(c[..])+multiset(d[..]); { assert b[..] == b[..i+j]; assert c[..] == c[..i]; assert d[..] == d[..j]; } //This lemma helps dafny see that after adding the next value from c to b the prefixes are still the same subsets. lemma lemmaInvSubsetTakeValueFromC (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat) requires i < |c|; requires j <= |d|; requires i + j < |b|; requires |c| + |d| == |b|; requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) requires b[i+j] == c[i] ensures multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j]) { assert c[..i]+[c[i]] == c[..i+1]; assert b[..i+j+1] == b[..i+j] + [b[i+j]]; assert multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j]); } //This lemma helps dafny see that after adding the next value from d to b the prefixes are still the same subsets. lemma{:verify true} lemmaInvSubsetTakeValueFromD (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat) requires i <= |c|; requires j < |d|; requires i + j < |b|; requires |c| + |d| == |b|; requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j]) requires b[i+j] == d[j] ensures multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1]) { assert d[..j]+[d[j]] == d[..j+1]; assert b[..i+j+1] == b[..i+j] + [b[i+j]]; assert multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1]); } method Main() { var a := new int[3] [4, 8, 6]; var q0 := a[..]; assert q0 == [4,8,6]; a := MergeSort(a); assert a.Length == |q0| && multiset(a[..]) == multiset(q0); print "\nThe sorted version of ", q0, " is ", a[..]; assert Sorted(a[..]); assert a[..] == [4, 6, 8]; a := new int[5] [3, 8, 5, -1, 10]; q0 := a[..]; assert q0 == [3, 8, 5, -1, 10]; a := MergeSort(a); assert a.Length == |q0| && multiset(a[..]) == multiset(q0); print "\nThe sorted version of ", q0, " is ", a[..]; assert Sorted(a[..]); //assert a[..] == [-1, 3, 5, 8, 10]; }
AssertivePrograming_tmp_tmpwf43uz0e_MergeSort.dfy
006
006
Dafny program: 006
// method CountLessThan(numbers: set<int>, threshold: int) returns (count: int) // // ensures count == |set i | i in numbers && i < threshold| // ensures count == |SetLessThan(numbers, threshold)| // { // count := 0; // var ss := numbers; // while ss != {} // decreases |ss| // { // var i: int :| i in ss; // ss := ss - {i}; // if i < threshold { // count := count + 1; // } // } // assert count == |SetLessThan(numbers, threshold)|; // // assert count == |set i | i in numbers && i < threshold|; // } function SetLessThan(numbers: set<int>, threshold: int): set<int> { set i | i in numbers && i < threshold } method Main() { // var s: set<int> := {1, 2, 3, 4, 5}; // var c: int := CountLessThan(s, 4); // print c; // assert c == 3; // if you manualy create set and sequence with same elements, |s|==|t| works var t: seq<int> := [1, 2, 3]; var s: set<int> := {1, 2, 3}; // but if you create set from the sequence with distinct elements it does not understand that |s|==|t| // Dafny has problems when reasoning about set sizes ==> s := set x | x in t; // assert |s| == |t|; // not verifying // assert |s| == 3; // not verifying // other expriments set_memebrship_implies_cardinality(s, set x | x in t); // s and the other argument is the same thing var s2 : set<int> := set x | x in t; s2 := {1, 2, 3}; // assert |s| == |s2|; // may not hold set_memebrship_implies_cardinality(s, s2); } lemma set_memebrship_implies_cardinality_helper<A>(s: set<A>, t: set<A>, s_size: int) requires s_size >= 0 && s_size == |s| requires forall x :: x in s <==> x in t ensures |s| == |t| if s_size == 0 { } else { var s_hd; // assign s_hd to a value *such that* s_hd is in s (see such_that expressions) s_hd :| s_hd in s; set_memebrship_implies_cardinality_helper(s - {s_hd}, t - {s_hd}, s_size - 1); } } lemma set_memebrship_implies_cardinality<A>(s: set<A>, t: set<A>) requires forall x :: x in s <==> x in t ensures |s| == |t| { set_memebrship_implies_cardinality_helper(s, t, |s|); } /* lemma Bijection(arr: seq<int>, s: set<int>) // returns (bool) requires sorted(arr) // requires forall x, y :: x in s && y in s && x != y ==> x < y ensures |s| == |arr| { var mapping: map<int, int> := map[]; // Establish the bijection for i := 0 to |arr| { mapping := mapping[arr[i]:= arr[i]]; } // Prove injectiveness // Prove surjectiveness // assert forall x :: x in s ==> exists i :: 0 <= i < |arr|-1 && arr[i] == x; // Conclude equinumerosity // assert |s| == |arr|; // return true; } */ function seqSet(nums: seq<int>, index: nat): set<int> { set x | 0 <= x < index < |nums| :: nums[x] } lemma containsDuplicateI(nums: seq<int>) returns (containsDuplicate: bool) ensures containsDuplicate ==> exists i,j :: 0 <= i < j < |nums| && nums[i] == nums[j] { var windowGhost: set<int> := {}; var windowSet: set<int> := {}; for i:= 0 to |nums| // invariant forall x :: x in windowSet ==> x in nums { windowGhost := windowSet; if nums[i] in windowSet { // does not verify // if nums[i] in seqSet(nums, i) { //verifies return true; } windowSet := windowSet + {nums[i]}; } return false; } // lemma numElemsOfSet(a: seq<int>) // requires sorted(a) // { // assert distinct(a); // var s := set x | x in a; // assert forall x :: x in s ==> x in a[..]; // assert forall x :: x in a ==> x in s; // assert |s| == |a|; // } // lemma CardinalitySetEqualsArray(a: seq<int>, s: set<int>) // requires s == set x | x in a // requires distinct(a) // ensures |s| == |a| // { // assert forall x :: x in s ==> exists i :: 0 <= i < |a| && a[i] == x; // assert forall i, j :: 0 <= i < |a| && 0 <= j < |a| && i != j ==> a[i] != a[j]; // // Assert that each element in the array is in the set // assert forall i :: 0 <= i < |a| ==> a[i] in s; // // Assert that the set contains exactly the elements in the array // assert s == set x | x in a; // // Assert that the set is a subset of the array // assert forall x :: x in s <==> x in a; // // Conclude the equivalence // assert |s| == |a|; // } /* lemma memebrship_implies_cardinality_helper<A>(s: set<A>, t: seq<A>, s_size: int) requires s_size >= 0 && s_size == |s| requires forall x :: x in s <==> x in t requires forall i, j :: (0 <= i < |t| && 0 <= j < |t| && i != j ) ==> t[i] != t[j] requires |set x | x in t| == |t| ensures |s| == |t| if s_size == 0 { } else { var t_hd; t_hd := t[0]; ghost var t_h := set x | x in t[1..]; memebrship_implies_cardinality_helper(s - {t_hd}, t[1..], s_size - 1); } } lemma memebrship_implies_cardinality<A>(s: set<A>, t: seq<A>) requires forall x :: x in s <==> x in t ensures |s| == |t| { memebrship_implies_cardinality_helper(s, t, |s|); } */ lemma set_memebrship_implies_equality_helper<A>(s: set<A>, t: set<A>, s_size: int) requires s_size >= 0 && s_size == |s| requires forall x :: x in s <==> x in t ensures s == t if s_size == 0 { } else { var s_hd; // assign s_hd to a value *such that* s_hd is in s (see such_that expressions) s_hd :| s_hd in s; set_memebrship_implies_equality_helper(s - {s_hd}, t - {s_hd}, s_size - 1); } } lemma set_memebrship_implies_equality<A>(s: set<A>, t: set<A>) requires forall x :: x in s <==> x in t ensures s == t { set_memebrship_implies_equality_helper(s, t, |s|); } // TODO play with this for keys==Contents lemma set_seq_equality(s: set<int>, t: seq<int>) requires distinct(t) requires forall x :: x in t <==> x in s { var s2 : set<int> := set x | x in t; set_memebrship_implies_equality_helper(s, s2, |s|); // assert |s2| == |t|; // assert |s| == |t|; } ghost predicate SortedSeq(a: seq<int>) //sequence is sorted from left to right { (forall i,j :: 0<= i< j < |a| ==> ( a[i] < a[j] )) } method GetInsertIndex(a: array<int>, limit: int, x:int) returns (idx:int) // get index so that array stays sorted requires x !in a[..] requires 0 <= limit <= a.Length requires SortedSeq(a[..limit]) ensures 0<= idx <= limit ensures SortedSeq(a[..limit]) ensures idx > 0 ==> a[idx-1]< x ensures idx < limit ==> x < a[idx] { idx := limit; for i := 0 to limit { if x < a[i] { idx := i; break; } } } predicate sorted(a: seq<int>) { forall i,j :: 0 <= i < j < |a| ==> a[i] < a[j] } predicate distinct(a: seq<int>) { forall i,j :: (0 <= i < |a| && 0 <= j < |a| && i != j) ==> a[i] != a[j] } predicate sorted_eq(a: seq<int>) { forall i,j :: 0 <= i < j < |a| ==> a[i] <= a[j] } predicate lessThan(a:seq<int>, key:int) { forall i :: 0 <= i < |a| ==> a[i] < key } predicate greaterThan(a:seq<int>, key:int) { forall i :: 0 <= i < |a| ==> a[i] > key } predicate greaterEqualThan(a:seq<int>, key:int) { forall i :: 0 <= i < |a| ==> a[i] >= key } /* method InsertSorted(a: array<int>, key: int ) returns (b: array<int>) requires sorted_eq(a[..]) ensures sorted_eq(b[..]) { b:= new int[a.Length + 1]; ghost var k := 0; b[0] := key; ghost var a' := a[..]; var i:= 0; while (i < a.Length) modifies b { if(a[i]<key) { b[i]:= a[i]; b[i+1] := key; k := i+1; } else if (a[i] >= key) { b[i+1] := a[i]; } i := i+1; } } */ lemma DistributiveLemma(a: seq<bool>, b: seq<bool>) ensures count(a + b) == count(a) + count(b) { if a == [] { } else { DistributiveLemma(a[1..], b); } } function count(a: seq<bool>): nat { if |a| == 0 then 0 else (if a[0] then 1 else 0) + count(a[1..]) } lemma DistributiveIn(a: seq<int>, b:seq<int>, k:int, key:int) requires |a| + 1 == |b| requires 0 <= k <= |a| requires b == a[..k] + [key] + a[k..] ensures forall i :: 0 <= i < |a| ==> a[i] in b { } lemma DistributiveGreater(a: seq<int>, b:seq<int>, k:int, key:int) requires |a| + 1 == |b| requires 0 <= k <= |a| requires b == a[..k] + [key] + a[k..] requires forall j :: 0 <= j < |a| ==> a[j] > 0 requires key > 0 ensures forall i :: 0 <= i < |b| ==> b[i] > 0 { // assert ((forall j :: 0 <= j < k ==> b[j] > 0) && (forall j :: k <= j < |a| ==> b[j] > 0)) ==> (forall j :: 0 <= j < |b| ==> b[j] > 0); } // verifies in more than 45 seconds, but less than 100 seconds method InsertIntoSorted(a: array<int>, limit:int, key:int) returns (b: array<int>) requires key > 0 requires key !in a[..] requires 0 <= limit < a.Length requires forall i :: 0 <= i < limit ==> a[i] > 0 requires forall i :: limit <= i < a.Length ==> a[i] == 0 requires sorted(a[..limit]) ensures b.Length == a.Length ensures sorted(b[..(limit+ 1)]) ensures forall i :: limit + 1 <= i < b.Length ==> b[i] == 0 ensures forall i :: 0 <= i < limit ==> a[i] in b[..] ensures forall i :: 0 <= i < limit + 1 ==> b[i] > 0 { b:= new int[a.Length]; ghost var k := 0; b[0] := key; ghost var a' := a[..]; var i:= 0; while (i < limit) modifies b { if(a[i]<key) { b[i]:= a[i]; b[i+1] := key; k := i+1; } else if (a[i] >= key) { b[i+1] := a[i]; } i := i+1; } // assert b[..limit+1] == a[..k] + [key] + a[k..limit]; DistributiveIn(a[..limit], b[..limit+1], k, key); DistributiveGreater(a[..limit], b[..limit+1], k, key); // assert forall i :: 0 <= i < limit + 1 ==> b[i] > 0; ghost var b' := b[..]; i := limit + 1; while i < b.Length { b[i] := 0; i := i + 1; } }
// method CountLessThan(numbers: set<int>, threshold: int) returns (count: int) // // ensures count == |set i | i in numbers && i < threshold| // ensures count == |SetLessThan(numbers, threshold)| // { // count := 0; // var ss := numbers; // while ss != {} // decreases |ss| // { // var i: int :| i in ss; // ss := ss - {i}; // if i < threshold { // count := count + 1; // } // } // assert count == |SetLessThan(numbers, threshold)|; // // assert count == |set i | i in numbers && i < threshold|; // } function SetLessThan(numbers: set<int>, threshold: int): set<int> { set i | i in numbers && i < threshold } method Main() { // var s: set<int> := {1, 2, 3, 4, 5}; // var c: int := CountLessThan(s, 4); // print c; // assert c == 3; // if you manualy create set and sequence with same elements, |s|==|t| works var t: seq<int> := [1, 2, 3]; var s: set<int> := {1, 2, 3}; assert |s| == 3; assert |s| == |t|; // but if you create set from the sequence with distinct elements it does not understand that |s|==|t| // Dafny has problems when reasoning about set sizes ==> s := set x | x in t; assert forall x :: x in t ==> x in s; assert forall x :: x in s ==> x in t; assert forall x :: x in s <==> x in t; assert forall i, j :: 0 <= i < |t| && 0 <= j < |t| && i !=j ==> t[i] != t[j]; assert |t| == 3; // assert |s| == |t|; // not verifying // assert |s| == 3; // not verifying // other expriments set_memebrship_implies_cardinality(s, set x | x in t); // s and the other argument is the same thing var s2 : set<int> := set x | x in t; assert |s| == |s2|; s2 := {1, 2, 3}; // assert |s| == |s2|; // may not hold set_memebrship_implies_cardinality(s, s2); assert |s| == |s2|; // after lemma it holds } lemma set_memebrship_implies_cardinality_helper<A>(s: set<A>, t: set<A>, s_size: int) requires s_size >= 0 && s_size == |s| requires forall x :: x in s <==> x in t ensures |s| == |t| decreases s_size { if s_size == 0 { } else { var s_hd; // assign s_hd to a value *such that* s_hd is in s (see such_that expressions) s_hd :| s_hd in s; set_memebrship_implies_cardinality_helper(s - {s_hd}, t - {s_hd}, s_size - 1); } } lemma set_memebrship_implies_cardinality<A>(s: set<A>, t: set<A>) requires forall x :: x in s <==> x in t ensures |s| == |t| { set_memebrship_implies_cardinality_helper(s, t, |s|); } /* lemma Bijection(arr: seq<int>, s: set<int>) // returns (bool) requires sorted(arr) // requires forall x, y :: x in s && y in s && x != y ==> x < y ensures |s| == |arr| { var mapping: map<int, int> := map[]; // Establish the bijection for i := 0 to |arr| { mapping := mapping[arr[i]:= arr[i]]; } // Prove injectiveness assert forall i, j :: (0 <= i < |arr|-1 && 0 <= j < |arr|-1 && i != j )==> mapping[arr[i]] != mapping[arr[j]]; // Prove surjectiveness // assert forall x :: x in s ==> exists i :: 0 <= i < |arr|-1 && arr[i] == x; // Conclude equinumerosity // assert |s| == |arr|; // return true; } */ function seqSet(nums: seq<int>, index: nat): set<int> { set x | 0 <= x < index < |nums| :: nums[x] } lemma containsDuplicateI(nums: seq<int>) returns (containsDuplicate: bool) ensures containsDuplicate ==> exists i,j :: 0 <= i < j < |nums| && nums[i] == nums[j] { var windowGhost: set<int> := {}; var windowSet: set<int> := {}; for i:= 0 to |nums| invariant 0 <= i <= |nums| invariant forall j :: 0 <= j < i < |nums| ==> nums[j] in windowSet // invariant forall x :: x in windowSet ==> x in nums invariant forall x :: x in windowSet ==> x in nums[0..i] invariant seqSet(nums, i) <= windowSet { windowGhost := windowSet; if nums[i] in windowSet { // does not verify // if nums[i] in seqSet(nums, i) { //verifies return true; } windowSet := windowSet + {nums[i]}; } return false; } // lemma numElemsOfSet(a: seq<int>) // requires sorted(a) // { // assert distinct(a); // var s := set x | x in a; // assert forall x :: x in s ==> x in a[..]; // assert forall x :: x in a ==> x in s; // assert |s| == |a|; // } // lemma CardinalitySetEqualsArray(a: seq<int>, s: set<int>) // requires s == set x | x in a // requires distinct(a) // ensures |s| == |a| // { // assert forall x :: x in s ==> exists i :: 0 <= i < |a| && a[i] == x; // assert forall i, j :: 0 <= i < |a| && 0 <= j < |a| && i != j ==> a[i] != a[j]; // // Assert that each element in the array is in the set // assert forall i :: 0 <= i < |a| ==> a[i] in s; // // Assert that the set contains exactly the elements in the array // assert s == set x | x in a; // // Assert that the set is a subset of the array // assert forall x :: x in s <==> x in a; // // Conclude the equivalence // assert |s| == |a|; // } /* lemma memebrship_implies_cardinality_helper<A>(s: set<A>, t: seq<A>, s_size: int) requires s_size >= 0 && s_size == |s| requires forall x :: x in s <==> x in t requires forall i, j :: (0 <= i < |t| && 0 <= j < |t| && i != j ) ==> t[i] != t[j] requires |set x | x in t| == |t| ensures |s| == |t| decreases s_size { if s_size == 0 { } else { var t_hd; t_hd := t[0]; assert t_hd in s; ghost var t_h := set x | x in t[1..]; assert |t_h| == |t[1..]|; memebrship_implies_cardinality_helper(s - {t_hd}, t[1..], s_size - 1); } } lemma memebrship_implies_cardinality<A>(s: set<A>, t: seq<A>) requires forall x :: x in s <==> x in t ensures |s| == |t| { memebrship_implies_cardinality_helper(s, t, |s|); } */ lemma set_memebrship_implies_equality_helper<A>(s: set<A>, t: set<A>, s_size: int) requires s_size >= 0 && s_size == |s| requires forall x :: x in s <==> x in t ensures s == t decreases s_size { if s_size == 0 { } else { var s_hd; // assign s_hd to a value *such that* s_hd is in s (see such_that expressions) s_hd :| s_hd in s; set_memebrship_implies_equality_helper(s - {s_hd}, t - {s_hd}, s_size - 1); } } lemma set_memebrship_implies_equality<A>(s: set<A>, t: set<A>) requires forall x :: x in s <==> x in t ensures s == t { set_memebrship_implies_equality_helper(s, t, |s|); } // TODO play with this for keys==Contents lemma set_seq_equality(s: set<int>, t: seq<int>) requires distinct(t) requires forall x :: x in t <==> x in s { var s2 : set<int> := set x | x in t; set_memebrship_implies_equality_helper(s, s2, |s|); assert |s2| == |s|; // assert |s2| == |t|; // assert |s| == |t|; } ghost predicate SortedSeq(a: seq<int>) //sequence is sorted from left to right { (forall i,j :: 0<= i< j < |a| ==> ( a[i] < a[j] )) } method GetInsertIndex(a: array<int>, limit: int, x:int) returns (idx:int) // get index so that array stays sorted requires x !in a[..] requires 0 <= limit <= a.Length requires SortedSeq(a[..limit]) ensures 0<= idx <= limit ensures SortedSeq(a[..limit]) ensures idx > 0 ==> a[idx-1]< x ensures idx < limit ==> x < a[idx] { idx := limit; for i := 0 to limit invariant i>0 ==> x > a[i-1] { if x < a[i] { idx := i; break; } } } predicate sorted(a: seq<int>) { forall i,j :: 0 <= i < j < |a| ==> a[i] < a[j] } predicate distinct(a: seq<int>) { forall i,j :: (0 <= i < |a| && 0 <= j < |a| && i != j) ==> a[i] != a[j] } predicate sorted_eq(a: seq<int>) { forall i,j :: 0 <= i < j < |a| ==> a[i] <= a[j] } predicate lessThan(a:seq<int>, key:int) { forall i :: 0 <= i < |a| ==> a[i] < key } predicate greaterThan(a:seq<int>, key:int) { forall i :: 0 <= i < |a| ==> a[i] > key } predicate greaterEqualThan(a:seq<int>, key:int) { forall i :: 0 <= i < |a| ==> a[i] >= key } /* method InsertSorted(a: array<int>, key: int ) returns (b: array<int>) requires sorted_eq(a[..]) ensures sorted_eq(b[..]) { b:= new int[a.Length + 1]; ghost var k := 0; b[0] := key; ghost var a' := a[..]; var i:= 0; while (i < a.Length) modifies b invariant 0 <= k <= i <= a.Length invariant b.Length == a.Length + 1 invariant a[..] == a' invariant lessThan(a[..i], key) ==> i == k invariant lessThan(a[..k], key) invariant b[..k] == a[..k] invariant b[k] == key invariant k < i ==> b[k+1..i+1] == a[k..i] invariant k < i ==> greaterEqualThan(b[k+1..i+1], key) invariant 0 <= k < b.Length && b[k] == key { if(a[i]<key) { b[i]:= a[i]; b[i+1] := key; k := i+1; } else if (a[i] >= key) { b[i+1] := a[i]; } i := i+1; } assert b[..] == a[..k] + [key] + a[k..]; } */ lemma DistributiveLemma(a: seq<bool>, b: seq<bool>) ensures count(a + b) == count(a) + count(b) { if a == [] { assert a + b == b; } else { DistributiveLemma(a[1..], b); assert a + b == [a[0]] + (a[1..] + b); } } function count(a: seq<bool>): nat { if |a| == 0 then 0 else (if a[0] then 1 else 0) + count(a[1..]) } lemma DistributiveIn(a: seq<int>, b:seq<int>, k:int, key:int) requires |a| + 1 == |b| requires 0 <= k <= |a| requires b == a[..k] + [key] + a[k..] ensures forall i :: 0 <= i < |a| ==> a[i] in b { assert forall j :: 0 <= j < k ==> a[j] in b; assert forall j :: k <= j < |a| ==> a[j] in b; assert ((forall j :: 0 <= j < k ==> a[j] in b) && (forall j :: k <= j < |a| ==> a[j] in b)) ==> (forall j :: 0 <= j < |a| ==> a[j] in b); assert forall j :: 0 <= j < |a| ==> a[j] in b; } lemma DistributiveGreater(a: seq<int>, b:seq<int>, k:int, key:int) requires |a| + 1 == |b| requires 0 <= k <= |a| requires b == a[..k] + [key] + a[k..] requires forall j :: 0 <= j < |a| ==> a[j] > 0 requires key > 0 ensures forall i :: 0 <= i < |b| ==> b[i] > 0 { // assert ((forall j :: 0 <= j < k ==> b[j] > 0) && (forall j :: k <= j < |a| ==> b[j] > 0)) ==> (forall j :: 0 <= j < |b| ==> b[j] > 0); assert forall j :: 0 <= j < |b| ==> b[j] > 0; } // verifies in more than 45 seconds, but less than 100 seconds method InsertIntoSorted(a: array<int>, limit:int, key:int) returns (b: array<int>) requires key > 0 requires key !in a[..] requires 0 <= limit < a.Length requires forall i :: 0 <= i < limit ==> a[i] > 0 requires forall i :: limit <= i < a.Length ==> a[i] == 0 requires sorted(a[..limit]) ensures b.Length == a.Length ensures sorted(b[..(limit+ 1)]) ensures forall i :: limit + 1 <= i < b.Length ==> b[i] == 0 ensures forall i :: 0 <= i < limit ==> a[i] in b[..] ensures forall i :: 0 <= i < limit + 1 ==> b[i] > 0 { b:= new int[a.Length]; ghost var k := 0; b[0] := key; ghost var a' := a[..]; var i:= 0; while (i < limit) modifies b invariant 0 <= k <= i <= limit invariant b.Length == a.Length invariant a[..] == a' invariant lessThan(a[..i], key) ==> i == k invariant lessThan(a[..k], key) invariant b[..k] == a[..k] invariant b[k] == key invariant k < i ==> b[k+1..i+1] == a[k..i] invariant k < i ==> greaterThan(b[k+1..i+1], key) invariant 0 <= k < b.Length && b[k] == key { if(a[i]<key) { b[i]:= a[i]; b[i+1] := key; k := i+1; } else if (a[i] >= key) { b[i+1] := a[i]; } i := i+1; } assert b[..limit+1] == a[..k] + [key] + a[k..limit]; assert sorted(b[..limit+1]); // assert b[..limit+1] == a[..k] + [key] + a[k..limit]; DistributiveIn(a[..limit], b[..limit+1], k, key); assert forall i :: 0 <= i < limit ==> a[i] in b[..limit+1]; DistributiveGreater(a[..limit], b[..limit+1], k, key); // assert forall i :: 0 <= i < limit + 1 ==> b[i] > 0; ghost var b' := b[..]; i := limit + 1; while i < b.Length invariant limit + 1 <= i <= b.Length invariant forall j :: limit + 1 <= j < i ==> b[j] == 0 invariant b[..limit+1] == b'[..limit+1] invariant sorted(b[..limit+1]) { b[i] := 0; i := i + 1; } assert forall i :: limit + 1 <= i < b.Length ==> b[i] == 0; }
BPTree-verif_tmp_tmpq1z6xm1d_Utils.dfy
009
009
Dafny program: 009
//Bubblesort CS 494 submission //References: https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny/69365785#69365785 // predicate checks if elements of a are in ascending order, two additional conditions are added to allow us to sort in specific range within array predicate sorted(a:array<int>, from:int, to:int) requires a != null; // requires array to have n amount of elements reads a; requires 0 <= from <= to <= a.Length; // pre condition checks that from is the start of the range and to is the end of the range, requires values to be within 0 - a.Length { forall x, y :: from <= x < y < to ==> a[x] <= a[y] } //helps ensure swapping is valid, it is used inside the nested while loop to make sure linear order is being kept predicate pivot(a:array<int>, to:int, pvt:int) requires a != null; // requires array to have n amount of elements reads a; requires 0 <= pvt < to <= a.Length; { forall x, y :: 0 <= x < pvt < y < to ==> a[x] <= a[y] // all values within the array should be in ascending order } // Here having the algorithm for the bubblesort method BubbleSort (a: array<int>) requires a != null && a.Length > 0; // makes sure a is not empty and length is greater than 0 modifies a; // as method runs, we are changing a ensures sorted(a, 0, a.Length); // makes sure elements of array a are sorted from 0 - a.Length ensures multiset(a[..]) == multiset(old(a[..])); // Since a is being modified, we deference the heap //and compare the previous elements to current elements. { var i := 1; while (i < a.Length) { var j := i; //this while loop inherits any previous pre/post conditions. It checks that while (j > 0) { // Here it also simplifies the remaining invariants to handle the empty array. if (a[j-1] > a[j]) { // reverse iterate through range within the array a[j - 1], a[j] := a[j], a[j - 1]; // swaps objects if the IF condition is met } j := j - 1; // decrement j } i := i+1; // increment i } }
//Bubblesort CS 494 submission //References: https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny/69365785#69365785 // predicate checks if elements of a are in ascending order, two additional conditions are added to allow us to sort in specific range within array predicate sorted(a:array<int>, from:int, to:int) requires a != null; // requires array to have n amount of elements reads a; requires 0 <= from <= to <= a.Length; // pre condition checks that from is the start of the range and to is the end of the range, requires values to be within 0 - a.Length { forall x, y :: from <= x < y < to ==> a[x] <= a[y] } //helps ensure swapping is valid, it is used inside the nested while loop to make sure linear order is being kept predicate pivot(a:array<int>, to:int, pvt:int) requires a != null; // requires array to have n amount of elements reads a; requires 0 <= pvt < to <= a.Length; { forall x, y :: 0 <= x < pvt < y < to ==> a[x] <= a[y] // all values within the array should be in ascending order } // Here having the algorithm for the bubblesort method BubbleSort (a: array<int>) requires a != null && a.Length > 0; // makes sure a is not empty and length is greater than 0 modifies a; // as method runs, we are changing a ensures sorted(a, 0, a.Length); // makes sure elements of array a are sorted from 0 - a.Length ensures multiset(a[..]) == multiset(old(a[..])); // Since a is being modified, we deference the heap //and compare the previous elements to current elements. { var i := 1; while (i < a.Length) invariant i <= a.Length; // more-or-less validates while loop condition during coputations invariant sorted(a, 0, i); // Checks that for each increment of i, the array stays sorted, causing the invariant multiset(a[..]) == multiset(old(a[..])); //makes sure elements that existed in previous heap for a are presnt in current run { var j := i; //this while loop inherits any previous pre/post conditions. It checks that while (j > 0) invariant multiset(a[..]) == multiset(old(a[..])); invariant sorted(a, 0, j); // O(n^2) runtime. Makes sure that a[0] - a[j] is sorted invariant sorted(a, j, i+1); // then makes sure from a[j] - a[i+1] is sorted invariant pivot(a, i+1, j); // important for ensuring that each computation is correct after swapping { // Here it also simplifies the remaining invariants to handle the empty array. if (a[j-1] > a[j]) { // reverse iterate through range within the array a[j - 1], a[j] := a[j], a[j - 1]; // swaps objects if the IF condition is met } j := j - 1; // decrement j } i := i+1; // increment i } }
CS494-final-project_tmp_tmp7nof55uq_bubblesort.dfy
010
010
Dafny program: 010
class LFUCache { var capacity : int; var cacheMap : map<int, (int, int)>; //key -> {value, freq} constructor(capacity: int) requires capacity > 0; ensures Valid(); { this.capacity := capacity; this.cacheMap := map[]; } predicate Valid() reads this; // reads this.freqMap.Values; { // general value check this.capacity > 0 && 0 <= |cacheMap| <= capacity && (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].1 >= 1)) && // frequency should always larger than 0 (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].0 >= 0)) // only allow positive values } method getLFUKey() returns (lfuKey : int) requires Valid(); requires |cacheMap| > 0; ensures Valid(); ensures lfuKey in cacheMap; ensures forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1; { var items := cacheMap.Items; var seenItems := {}; var anyItem :| anyItem in items; var minFreq := anyItem.1.1; lfuKey := anyItem.0; while items != {} { var item :| item in items; if (item.1.1 < minFreq) { lfuKey := item.0; minFreq := item.1.1; } items := items - { item }; seenItems := seenItems + { item }; } // assert forall k :: k in cacheMap ==> cacheMap[lfuKey].1 <= cacheMap[k].1; // ???? return lfuKey; } method get(key: int) returns (value: int) requires Valid(); modifies this; ensures Valid(); ensures key !in cacheMap ==> value == -1; ensures forall e :: e in old(cacheMap) <==> e in cacheMap; ensures forall e :: e in old(cacheMap) ==> (old(cacheMap[e].0) == cacheMap[e].0); ensures key in cacheMap ==> value == cacheMap[key].0 && old(cacheMap[key].1) == cacheMap[key].1-1; { if(key !in cacheMap) { value := -1; } else{ value := cacheMap[key].0; var oldFreq := cacheMap[key].1; var newV := (value, oldFreq + 1); cacheMap := cacheMap[key := newV]; } print "after get: "; print cacheMap; print "\n"; return value; } method put(key: int, value: int) requires Valid(); requires value > 0; modifies this ensures Valid(); { if (key in cacheMap) { var currFreq := cacheMap[key].1; cacheMap := cacheMap[key := (value, currFreq)]; } else { if (|cacheMap| < capacity) { cacheMap := cacheMap[key := (value, 1)]; } else { var LFUKey := getLFUKey(); ghost var oldMap := cacheMap; var newMap := cacheMap - {LFUKey}; cacheMap := newMap; ghost var oldCard := |oldMap|; ghost var newCard := |newMap|; cacheMap := cacheMap[key := (value, 1)]; } } print "after put: "; print cacheMap; print "\n"; } } method Main() { var LFUCache := new LFUCache(5); print "Cache Capacity = 5 \n"; print "PUT (1, 1) - "; LFUCache.put(1,1); print "PUT (2, 2) - "; LFUCache.put(2,2); print "PUT (3, 3) - "; LFUCache.put(3,3); print "GET (1) - "; var val := LFUCache.get(1); print "get(1) = "; print val; print "\n"; print "PUT (3, 5) - "; LFUCache.put(3,5); print "GET (3) - "; val := LFUCache.get(3); print "get(3) = "; print val; print "\n"; print "PUT (4, 6) - "; LFUCache.put(4,6); print "PUT (5, 7) - "; LFUCache.put(5,7); print "PUT (10, 100) - "; LFUCache.put(10,100); print "GET (2) - "; val := LFUCache.get(2); print "get(2) = "; print val; print "\n"; }
class LFUCache { var capacity : int; var cacheMap : map<int, (int, int)>; //key -> {value, freq} constructor(capacity: int) requires capacity > 0; ensures Valid(); { this.capacity := capacity; this.cacheMap := map[]; } predicate Valid() reads this; // reads this.freqMap.Values; { // general value check this.capacity > 0 && 0 <= |cacheMap| <= capacity && (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].1 >= 1)) && // frequency should always larger than 0 (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].0 >= 0)) // only allow positive values } method getLFUKey() returns (lfuKey : int) requires Valid(); requires |cacheMap| > 0; ensures Valid(); ensures lfuKey in cacheMap; ensures forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1; { var items := cacheMap.Items; var seenItems := {}; var anyItem :| anyItem in items; var minFreq := anyItem.1.1; lfuKey := anyItem.0; while items != {} decreases |items|; invariant cacheMap.Items >= items; invariant cacheMap.Items >= seenItems; invariant cacheMap.Items == seenItems + items; invariant lfuKey in cacheMap; invariant cacheMap[lfuKey].1 == minFreq; invariant forall e :: e in seenItems ==> minFreq <= e.1.1; invariant forall e :: e in seenItems ==> minFreq <= cacheMap[e.0].1; invariant forall e :: e in seenItems ==> cacheMap[lfuKey].1 <= cacheMap[e.0].1; invariant exists e :: e in seenItems + items ==> minFreq == e.1.1; { var item :| item in items; if (item.1.1 < minFreq) { lfuKey := item.0; minFreq := item.1.1; } items := items - { item }; seenItems := seenItems + { item }; } assert seenItems == cacheMap.Items; assert cacheMap[lfuKey].1 == minFreq; assert forall e :: e in seenItems ==> minFreq <= e.1.1; assert forall e :: e in cacheMap.Items ==> minFreq <= e.1.1; assert forall k :: k in seenItems ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1; assert forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1; // assert forall k :: k in cacheMap ==> cacheMap[lfuKey].1 <= cacheMap[k].1; // ???? return lfuKey; } method get(key: int) returns (value: int) requires Valid(); modifies this; ensures Valid(); ensures key !in cacheMap ==> value == -1; ensures forall e :: e in old(cacheMap) <==> e in cacheMap; ensures forall e :: e in old(cacheMap) ==> (old(cacheMap[e].0) == cacheMap[e].0); ensures key in cacheMap ==> value == cacheMap[key].0 && old(cacheMap[key].1) == cacheMap[key].1-1; { assert key in cacheMap ==> cacheMap[key].0 >= 0; if(key !in cacheMap) { value := -1; } else{ assert key in cacheMap; assert cacheMap[key].0 >= 0; value := cacheMap[key].0; var oldFreq := cacheMap[key].1; var newV := (value, oldFreq + 1); cacheMap := cacheMap[key := newV]; } print "after get: "; print cacheMap; print "\n"; return value; } method put(key: int, value: int) requires Valid(); requires value > 0; modifies this ensures Valid(); { if (key in cacheMap) { var currFreq := cacheMap[key].1; cacheMap := cacheMap[key := (value, currFreq)]; } else { if (|cacheMap| < capacity) { cacheMap := cacheMap[key := (value, 1)]; } else { var LFUKey := getLFUKey(); assert LFUKey in cacheMap; assert |cacheMap| == capacity; ghost var oldMap := cacheMap; var newMap := cacheMap - {LFUKey}; cacheMap := newMap; assert newMap == cacheMap - {LFUKey}; assert LFUKey !in cacheMap; assert LFUKey in oldMap; ghost var oldCard := |oldMap|; ghost var newCard := |newMap|; assert |cacheMap.Keys| < |oldMap|; // ???? cacheMap := cacheMap[key := (value, 1)]; } } print "after put: "; print cacheMap; print "\n"; } } method Main() { var LFUCache := new LFUCache(5); print "Cache Capacity = 5 \n"; print "PUT (1, 1) - "; LFUCache.put(1,1); print "PUT (2, 2) - "; LFUCache.put(2,2); print "PUT (3, 3) - "; LFUCache.put(3,3); print "GET (1) - "; var val := LFUCache.get(1); print "get(1) = "; print val; print "\n"; print "PUT (3, 5) - "; LFUCache.put(3,5); print "GET (3) - "; val := LFUCache.get(3); print "get(3) = "; print val; print "\n"; print "PUT (4, 6) - "; LFUCache.put(4,6); print "PUT (5, 7) - "; LFUCache.put(5,7); print "PUT (10, 100) - "; LFUCache.put(10,100); print "GET (2) - "; val := LFUCache.get(2); print "get(2) = "; print val; print "\n"; }
CS5232_Project_tmp_tmpai_cfrng_LFUSimple.dfy
011
011
Dafny program: 011
iterator Gen(start: int) yields (x: int) yield ensures |xs| <= 10 && x == start + |xs| - 1 { var i := 0; while i < 10 invariant |xs| == i { x := start + i; yield; i := i + 1; } } method Main() { var i := new Gen(30); while true { var m := i.MoveNext(); if (!m) {break; } print i.x; } }
iterator Gen(start: int) yields (x: int) yield ensures |xs| <= 10 && x == start + |xs| - 1 { var i := 0; while i < 10 invariant |xs| == i { x := start + i; yield; i := i + 1; } } method Main() { var i := new Gen(30); while true invariant i.Valid() && fresh(i._new) decreases 10 - |i.xs| { var m := i.MoveNext(); if (!m) {break; } print i.x; } }
CS5232_Project_tmp_tmpai_cfrng_test.dfy
014
014
Dafny program: 014
method Max (x: nat, y:nat) returns (r:nat) ensures (r >= x && r >=y) ensures (r == x || r == y) { if (x >= y) { r := x;} else { r := y;} } method Test () { var result := Max(42, 73); } method m1 (x: int, y: int) returns (z: int) requires 0 < x < y ensures z >= 0 && z <= y && z != x { //assume 0 < x < y z := 0; } function fib (n: nat) : nat { if n == 0 then 1 else if n == 1 then 1 else fib(n -1) + fib (n-2) } method Fib (n: nat) returns (r:nat) ensures r == fib(n) { if (n == 0) { return 1; } r := 1; var next:=2; var i := 1; while i < n { var tmp:=next; next:= next + r; r:= tmp; i:= i + 1; } return r; } datatype List<T> = Nil | Cons(head: T, tail: List<T>) function add(l:List<int>) : int { match l case Nil => 0 case Cons(x, xs) => x + add(xs) } method addImp (l: List<int>) returns (s: int) ensures s == add(l) { var ll := l; s := 0; while ll != Nil { s := s + ll.head; ll:= ll.tail; } } method MaxA (a: array<int>) returns (m: int) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> a[i] <= m ensures exists i :: 0 <= i < a.Length && a[i] == m { m := a[0]; var i := 1; while i< a.Length { if a[i] > m { m:= a[i]; } i := i +1; } }
method Max (x: nat, y:nat) returns (r:nat) ensures (r >= x && r >=y) ensures (r == x || r == y) { if (x >= y) { r := x;} else { r := y;} } method Test () { var result := Max(42, 73); assert result == 73; } method m1 (x: int, y: int) returns (z: int) requires 0 < x < y ensures z >= 0 && z <= y && z != x { //assume 0 < x < y z := 0; } function fib (n: nat) : nat { if n == 0 then 1 else if n == 1 then 1 else fib(n -1) + fib (n-2) } method Fib (n: nat) returns (r:nat) ensures r == fib(n) { if (n == 0) { return 1; } r := 1; var next:=2; var i := 1; while i < n invariant 1 <= i <= n invariant r == fib(i) invariant next == fib(i+1) { var tmp:=next; next:= next + r; r:= tmp; i:= i + 1; } assert r == fib(n); return r; } datatype List<T> = Nil | Cons(head: T, tail: List<T>) function add(l:List<int>) : int { match l case Nil => 0 case Cons(x, xs) => x + add(xs) } method addImp (l: List<int>) returns (s: int) ensures s == add(l) { var ll := l; s := 0; while ll != Nil decreases ll invariant add(l) == s + add(ll) { s := s + ll.head; ll:= ll.tail; } assert s == add(l); } method MaxA (a: array<int>) returns (m: int) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> a[i] <= m ensures exists i :: 0 <= i < a.Length && a[i] == m { m := a[0]; var i := 1; while i< a.Length invariant 1 <= i <= a.Length invariant forall j :: 0 <= j < i ==> a[j] <=m invariant exists j :: 0 <= j < i && a[j] ==m { if a[i] > m { m:= a[i]; } i := i +1; } }
CVS-Projto1_tmp_tmpb1o0bu8z_Hoare.dfy
016
016
Dafny program: 016
//Exercicio 1.a) function sum (a:array<int>, i:int, j:int) :int reads a requires 0 <= i <= j <= a.Length { if i == j then 0 else a[j-1] + sum(a, i, j-1) } //Exercicio 1.b) method query (a:array<int>, i:int, j:int) returns (s:int) requires 0 <= i <= j <= a.Length ensures s == sum(a, i, j) { s := 0; var aux := i; while (aux < j) { s := s + a[aux]; aux := aux + 1; } return s; } //Exercicio 1.c) lemma queryLemma(a:array<int>, i:int, j:int, k:int) requires 0 <= i <= k <= j <= a.Length ensures sum(a,i,k) + sum(a,k,j) == sum(a,i,j) { } method queryFast (a:array<int>, c:array<int>, i:int, j:int) returns (r:int) requires is_prefix_sum_for(a,c) && 0 <= i <= j <= a.Length < c.Length ensures r == sum(a, i,j) { r := c[j] - c[i]; queryLemma(a,0,j,i); return r; } predicate is_prefix_sum_for (a:array<int>, c:array<int>) reads c, a { a.Length + 1 == c.Length && c[0] == 0 && forall j :: 1 <= j <= a.Length ==> c[j] == sum(a,0,j) } ///Exercicio 2. datatype List<T> = Nil | Cons(head: T, tail: List<T>) method from_array<T>(a: array<T>) returns (l: List<T>) requires a.Length > 0 ensures forall j::0 <= j < a.Length ==> mem(a[j],l) { var i:= a.Length-1; l:= Nil; while (i >= 0) { l := Cons(a[i], l); i := i - 1; } return l; } function mem<T(==)> (x: T, l:List<T>) : bool { match l case Nil => false case Cons(y,r)=> if (x==y) then true else mem(x,r) }
//Exercicio 1.a) function sum (a:array<int>, i:int, j:int) :int decreases j reads a requires 0 <= i <= j <= a.Length { if i == j then 0 else a[j-1] + sum(a, i, j-1) } //Exercicio 1.b) method query (a:array<int>, i:int, j:int) returns (s:int) requires 0 <= i <= j <= a.Length ensures s == sum(a, i, j) { s := 0; var aux := i; while (aux < j) invariant i <= aux <= j invariant s == sum(a, i, aux) decreases j - aux { s := s + a[aux]; aux := aux + 1; } return s; } //Exercicio 1.c) lemma queryLemma(a:array<int>, i:int, j:int, k:int) requires 0 <= i <= k <= j <= a.Length ensures sum(a,i,k) + sum(a,k,j) == sum(a,i,j) { } method queryFast (a:array<int>, c:array<int>, i:int, j:int) returns (r:int) requires is_prefix_sum_for(a,c) && 0 <= i <= j <= a.Length < c.Length ensures r == sum(a, i,j) { r := c[j] - c[i]; queryLemma(a,0,j,i); return r; } predicate is_prefix_sum_for (a:array<int>, c:array<int>) reads c, a { a.Length + 1 == c.Length && c[0] == 0 && forall j :: 1 <= j <= a.Length ==> c[j] == sum(a,0,j) } ///Exercicio 2. datatype List<T> = Nil | Cons(head: T, tail: List<T>) method from_array<T>(a: array<T>) returns (l: List<T>) requires a.Length > 0 ensures forall j::0 <= j < a.Length ==> mem(a[j],l) { var i:= a.Length-1; l:= Nil; while (i >= 0) invariant -1 <= i < a. Length invariant forall j:: i+1 <= j < a.Length ==> mem(a[j],l) { l := Cons(a[i], l); i := i - 1; } return l; } function mem<T(==)> (x: T, l:List<T>) : bool decreases l { match l case Nil => false case Cons(y,r)=> if (x==y) then true else mem(x,r) }
CVS-Projto1_tmp_tmpb1o0bu8z_proj1_proj1.dfy
018
018
Dafny program: 018
/* Cumulative Sums over Arrays */ /* Daniel Cavalheiro 57869 Pedro Nunes 57854 */ //(a) function sum(a: array<int>, i: int, j: int): int reads a requires 0 <= i <= j <= a.Length { if (i == j) then 0 else a[i] + sum(a, i+1, j) } //(b) method query(a: array<int>, i: int, j: int) returns (res:int) requires 0 <= i <= j <= a.Length ensures res == sum(a, i, j) { res := 0; var k := i; while(k < j) { res := res + a[k]; k := k + 1; } } //(c) predicate is_prefix_sum_for (a: array<int>, c: array<int>) requires a.Length + 1 == c.Length requires c[0] == 0 reads c, a { forall i: int :: 0 <= i < a.Length ==> c[i+1] == c[i] + a[i] } lemma aux(a: array<int>, c: array<int>, i: int, j: int) requires 0 <= i <= j <= a.Length requires a.Length + 1 == c.Length requires c[0] == 0 requires is_prefix_sum_for(a, c) ensures forall k: int :: i <= k <= j ==> sum(a, i, k) + sum(a, k, j) == c[k] - c[i] + c[j] - c[k] //sum(a, i, j) == c[j] - c[i] {} method queryFast(a: array<int>, c: array<int>, i: int, j: int) returns (r: int) requires a.Length + 1 == c.Length && c[0] == 0 requires 0 <= i <= j <= a.Length requires is_prefix_sum_for(a,c) ensures r == sum(a, i, j) { aux(a, c, i, j); r := c[j] - c[i]; } method Main() { var x := new int[10]; x[0], x[1], x[2], x[3] := 2, 2, 1, 5; var y := sum(x, 0, x.Length); //assert y == 10; var c := new int[11]; c[0], c[1], c[2], c[3], c[4] := 0, 2, 4, 5, 10; // var r := queryFast(x, c, 0, x.Length); }
/* Cumulative Sums over Arrays */ /* Daniel Cavalheiro 57869 Pedro Nunes 57854 */ //(a) function sum(a: array<int>, i: int, j: int): int reads a requires 0 <= i <= j <= a.Length decreases j - i { if (i == j) then 0 else a[i] + sum(a, i+1, j) } //(b) method query(a: array<int>, i: int, j: int) returns (res:int) requires 0 <= i <= j <= a.Length ensures res == sum(a, i, j) { res := 0; var k := i; while(k < j) invariant i <= k <= j <= a.Length invariant res + sum(a, k, j) == sum(a, i, j) { res := res + a[k]; k := k + 1; } } //(c) predicate is_prefix_sum_for (a: array<int>, c: array<int>) requires a.Length + 1 == c.Length requires c[0] == 0 reads c, a { forall i: int :: 0 <= i < a.Length ==> c[i+1] == c[i] + a[i] } lemma aux(a: array<int>, c: array<int>, i: int, j: int) requires 0 <= i <= j <= a.Length requires a.Length + 1 == c.Length requires c[0] == 0 requires is_prefix_sum_for(a, c) decreases j - i ensures forall k: int :: i <= k <= j ==> sum(a, i, k) + sum(a, k, j) == c[k] - c[i] + c[j] - c[k] //sum(a, i, j) == c[j] - c[i] {} method queryFast(a: array<int>, c: array<int>, i: int, j: int) returns (r: int) requires a.Length + 1 == c.Length && c[0] == 0 requires 0 <= i <= j <= a.Length requires is_prefix_sum_for(a,c) ensures r == sum(a, i, j) { aux(a, c, i, j); r := c[j] - c[i]; } method Main() { var x := new int[10]; x[0], x[1], x[2], x[3] := 2, 2, 1, 5; var y := sum(x, 0, x.Length); //assert y == 10; var c := new int[11]; c[0], c[1], c[2], c[3], c[4] := 0, 2, 4, 5, 10; // var r := queryFast(x, c, 0, x.Length); }
CVS-handout1_tmp_tmptm52no3k_1.dfy
019
019
Dafny program: 019
/* Functional Lists and Imperative Arrays */ /* Daniel Cavalheiro 57869 Pedro Nunes 57854 */ datatype List<T> = Nil | Cons(head: T, tail: List<T>) function length<T>(l: List<T>): nat { match l case Nil => 0 case Cons(_, t) => 1 + length(t) } predicate mem<T(==)> (l: List<T>, x: T) { match l case Nil => false case Cons(h, t) => if(h == x) then true else mem(t, x) } function at<T>(l: List<T>, i: nat): T requires i < length(l) { if i == 0 then l.head else at(l.tail, i - 1) } method from_array<T>(a: array<T>) returns (l: List<T>) requires a.Length >= 0 ensures length(l) == a.Length ensures forall i: int :: 0 <= i < length(l) ==> at(l, i) == a[i] ensures forall x :: mem(l, x) ==> exists i: int :: 0 <= i < length(l) && a[i] == x { l := Nil; var i: int := a.Length - 1; while(i >= 0) { l := Cons(a[i], l); i := i-1; } } method Main() { var l: List<int> := List.Cons(1, List.Cons(2, List.Cons(3, Nil))); var arr: array<int> := new int [3](i => i + 1); var t: List<int> := from_array(arr); print l; print "\n"; print t; print "\n"; print t == l; }
/* Functional Lists and Imperative Arrays */ /* Daniel Cavalheiro 57869 Pedro Nunes 57854 */ datatype List<T> = Nil | Cons(head: T, tail: List<T>) function length<T>(l: List<T>): nat { match l case Nil => 0 case Cons(_, t) => 1 + length(t) } predicate mem<T(==)> (l: List<T>, x: T) { match l case Nil => false case Cons(h, t) => if(h == x) then true else mem(t, x) } function at<T>(l: List<T>, i: nat): T requires i < length(l) { if i == 0 then l.head else at(l.tail, i - 1) } method from_array<T>(a: array<T>) returns (l: List<T>) requires a.Length >= 0 ensures length(l) == a.Length ensures forall i: int :: 0 <= i < length(l) ==> at(l, i) == a[i] ensures forall x :: mem(l, x) ==> exists i: int :: 0 <= i < length(l) && a[i] == x { l := Nil; var i: int := a.Length - 1; while(i >= 0) invariant -1 <= i <= a.Length - 1 invariant length(l) == a.Length - 1 - i invariant forall j: int :: i < j < a.Length ==> at(l,j-i-1) == a[j] invariant forall x :: mem(l, x) ==> exists k: int :: i < k < a.Length && a[k] == x { l := Cons(a[i], l); i := i-1; } } method Main() { var l: List<int> := List.Cons(1, List.Cons(2, List.Cons(3, Nil))); var arr: array<int> := new int [3](i => i + 1); var t: List<int> := from_array(arr); print l; print "\n"; print t; print "\n"; print t == l; }
CVS-handout1_tmp_tmptm52no3k_2.dfy
021
021
Dafny program: 021
method allDigits(s: string) returns (result: bool) ensures result <==> (forall i :: 0 <= i < |s| ==> s[i] in "0123456789") { result:=true ; for i := 0 to |s| { if ! (s[i] in "0123456789"){ return false; } } }
method allDigits(s: string) returns (result: bool) ensures result <==> (forall i :: 0 <= i < |s| ==> s[i] in "0123456789") { result:=true ; for i := 0 to |s| invariant result <==> (forall ii :: 0 <= ii < i ==> s[ii] in "0123456789") { if ! (s[i] in "0123456789"){ return false; } } }
Clover_all_digits.dfy
022
022
Dafny program: 022
method append(a:array<int>, b:int) returns (c:array<int>) ensures a[..] + [b] == c[..] { c := new int[a.Length+1]; var i:= 0; while (i < a.Length) { c[i] := a[i]; i:=i+1; } c[a.Length]:=b; }
method append(a:array<int>, b:int) returns (c:array<int>) ensures a[..] + [b] == c[..] { c := new int[a.Length+1]; var i:= 0; while (i < a.Length) invariant 0 <= i <= a.Length invariant forall ii::0<=ii<i ==> c[ii]==a[ii] { c[i] := a[i]; i:=i+1; } c[a.Length]:=b; }
Clover_array_append.dfy
023
023
Dafny program: 023
method concat(a:array<int>, b:array<int>) returns (c:array<int>) ensures c.Length==b.Length+a.Length ensures forall k :: 0 <= k < a.Length ==> c[k] == a[k] ensures forall k :: 0 <= k < b.Length ==> c[k+a.Length] == b[k] { c := new int[a.Length+b.Length]; var i:= 0; while (i < c.Length) { c[i] := if i<a.Length then a[i] else b[i-a.Length]; i:=i+1; } }
method concat(a:array<int>, b:array<int>) returns (c:array<int>) ensures c.Length==b.Length+a.Length ensures forall k :: 0 <= k < a.Length ==> c[k] == a[k] ensures forall k :: 0 <= k < b.Length ==> c[k+a.Length] == b[k] { c := new int[a.Length+b.Length]; var i:= 0; while (i < c.Length) invariant 0 <= i <= c.Length invariant if i<a.Length then c[..i]==a[..i] else c[..i]==a[..]+b[..(i-a.Length)] { c[i] := if i<a.Length then a[i] else b[i-a.Length]; i:=i+1; } }
Clover_array_concat.dfy
024
024
Dafny program: 024
method iter_copy<T(0)>(s: array<T>) returns (t: array<T>) ensures s.Length==t.Length ensures forall i::0<=i<s.Length ==> s[i]==t[i] { t := new T[s.Length]; var i:= 0; while (i < s.Length) { t[i] := s[i]; i:=i+1; } }
method iter_copy<T(0)>(s: array<T>) returns (t: array<T>) ensures s.Length==t.Length ensures forall i::0<=i<s.Length ==> s[i]==t[i] { t := new T[s.Length]; var i:= 0; while (i < s.Length) invariant 0 <= i <= s.Length invariant forall x :: 0 <= x < i ==> s[x] == t[x] { t[i] := s[i]; i:=i+1; } }
Clover_array_copy.dfy
025
025
Dafny program: 025
method arrayProduct(a: array<int>, b: array<int>) returns (c: array<int> ) requires a.Length==b.Length ensures c.Length==a.Length ensures forall i:: 0 <= i< a.Length==> a[i] * b[i]==c[i] { c:= new int[a.Length]; var i:=0; while i<a.Length { c[i]:=a[i]*b[i]; i:=i+1; } }
method arrayProduct(a: array<int>, b: array<int>) returns (c: array<int> ) requires a.Length==b.Length ensures c.Length==a.Length ensures forall i:: 0 <= i< a.Length==> a[i] * b[i]==c[i] { c:= new int[a.Length]; var i:=0; while i<a.Length invariant 0<=i<=a.Length invariant forall j:: 0 <= j< i==> a[j] * b[j]==c[j] { c[i]:=a[i]*b[i]; i:=i+1; } }
Clover_array_product.dfy
026
026
Dafny program: 026
method arraySum(a: array<int>, b: array<int>) returns (c: array<int> ) requires a.Length==b.Length ensures c.Length==a.Length ensures forall i:: 0 <= i< a.Length==> a[i] + b[i]==c[i] { c:= new int[a.Length]; var i:=0; while i<a.Length { c[i]:=a[i]+b[i]; i:=i+1; } }
method arraySum(a: array<int>, b: array<int>) returns (c: array<int> ) requires a.Length==b.Length ensures c.Length==a.Length ensures forall i:: 0 <= i< a.Length==> a[i] + b[i]==c[i] { c:= new int[a.Length]; var i:=0; while i<a.Length invariant 0<=i<=a.Length invariant forall j:: 0 <= j< i==> a[j] + b[j]==c[j] { c[i]:=a[i]+b[i]; i:=i+1; } }
Clover_array_sum.dfy
028
028
Dafny program: 028
method below_zero(operations: seq<int>) returns (s:array<int>, result:bool) ensures s.Length == |operations| + 1 ensures s[0]==0 ensures forall i :: 0 <= i < s.Length-1 ==> s[i+1]==s[i]+operations[i] ensures result == true ==> (exists i :: 1 <= i <= |operations| && s[i] < 0) ensures result == false ==> forall i :: 0 <= i < s.Length ==> s[i] >= 0 { result := false; s := new int[|operations| + 1]; var i := 0; s[i] := 0; while i < s.Length { if i>0{ s[i] := s[i - 1] + operations[i - 1]; } i := i + 1; } i:=0; while i < s.Length { if s[i] < 0 { result := true; return; } i := i + 1; } }
method below_zero(operations: seq<int>) returns (s:array<int>, result:bool) ensures s.Length == |operations| + 1 ensures s[0]==0 ensures forall i :: 0 <= i < s.Length-1 ==> s[i+1]==s[i]+operations[i] ensures result == true ==> (exists i :: 1 <= i <= |operations| && s[i] < 0) ensures result == false ==> forall i :: 0 <= i < s.Length ==> s[i] >= 0 { result := false; s := new int[|operations| + 1]; var i := 0; s[i] := 0; while i < s.Length invariant 0 <= i <= s.Length invariant s[0]==0 invariant s.Length == |operations| + 1 invariant forall x :: 0 <= x < i-1 ==> s[x+1]==s[x]+operations[x] { if i>0{ s[i] := s[i - 1] + operations[i - 1]; } i := i + 1; } i:=0; while i < s.Length invariant 0 <= i <= s.Length invariant forall x :: 0 <= x < i ==> s[x] >= 0 { if s[i] < 0 { result := true; return; } i := i + 1; } }
Clover_below_zero.dfy
029
029
Dafny program: 029
method BinarySearch(a: array<int>, key: int) returns (n: int) requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j] ensures 0<= n <=a.Length ensures forall i :: 0<= i < n ==> a[i] < key ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] < key ensures forall i :: n<= i < a.Length ==> a[i]>=key { var lo, hi := 0, a.Length; while lo<hi { var mid := (lo + hi) / 2; if a[mid] < key { lo := mid + 1; } else { hi := mid; } } n:=lo; }
method BinarySearch(a: array<int>, key: int) returns (n: int) requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j] ensures 0<= n <=a.Length ensures forall i :: 0<= i < n ==> a[i] < key ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] < key ensures forall i :: n<= i < a.Length ==> a[i]>=key { var lo, hi := 0, a.Length; while lo<hi invariant 0<= lo <= hi <= a.Length invariant forall i :: 0<=i<lo ==> a[i] < key invariant forall i :: hi<=i<a.Length ==> a[i] >= key { var mid := (lo + hi) / 2; if a[mid] < key { lo := mid + 1; } else { hi := mid; } } n:=lo; }
Clover_binary_search.dfy
030
030
Dafny program: 030
method BubbleSort(a: array<int>) modifies a ensures forall i,j::0<= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..])==multiset(old(a[..])) { var i := a.Length - 1; while (i > 0) { var j := 0; while (j < i) { if (a[j] > a[j + 1]) { a[j], a[j + 1] := a[j + 1], a[j]; } j := j + 1; } i := i - 1; } }
method BubbleSort(a: array<int>) modifies a ensures forall i,j::0<= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..])==multiset(old(a[..])) { var i := a.Length - 1; while (i > 0) invariant i < 0 ==> a.Length == 0 invariant -1 <= i < a.Length invariant forall ii,jj::i <= ii< jj <a.Length ==> a[ii] <= a[jj] invariant forall k,k'::0<=k<=i<k'<a.Length==>a[k]<=a[k'] invariant multiset(a[..])==multiset(old(a[..])) { var j := 0; while (j < i) invariant 0 < i < a.Length && 0 <= j <= i invariant forall ii,jj::i<= ii <= jj <a.Length ==> a[ii] <= a[jj] invariant forall k, k'::0<=k<=i<k'<a.Length==>a[k]<=a[k'] invariant forall k :: 0 <= k <= j ==> a[k] <= a[j] invariant multiset(a[..])==multiset(old(a[..])) { if (a[j] > a[j + 1]) { a[j], a[j + 1] := a[j + 1], a[j]; } j := j + 1; } i := i - 1; } }
Clover_bubble_sort.dfy
031
031
Dafny program: 031
method CalDiv() returns (x:int, y:int) ensures x==191/7 ensures y==191%7 { x, y := 0, 191; while 7 <= y { x := x+1; y:=191-7*x; } }
method CalDiv() returns (x:int, y:int) ensures x==191/7 ensures y==191%7 { x, y := 0, 191; while 7 <= y invariant 0 <= y && 7 * x + y == 191 { x := x+1; y:=191-7*x; } }
Clover_cal_ans.dfy
032
032
Dafny program: 032
method Sum(N:int) returns (s:int) requires N >= 0 ensures s == N * (N + 1) / 2 { var n := 0; s := 0; while n != N { n := n + 1; s := s + n; } }
method Sum(N:int) returns (s:int) requires N >= 0 ensures s == N * (N + 1) / 2 { var n := 0; s := 0; while n != N invariant 0 <= n <= N invariant s == n * (n + 1) / 2 { n := n + 1; s := s + n; } }
Clover_cal_sum.dfy
033
033
Dafny program: 033
method CanyonSearch(a: array<int>, b: array<int>) returns (d:nat) requires a.Length !=0 && b.Length!=0 requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j] requires forall i,j :: 0<=i<j<b.Length ==> b[i]<=b[j] ensures exists i,j:: 0<=i<a.Length && 0<=j<b.Length && d==if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]) ensures forall i,j:: 0<=i<a.Length && 0<=j<b.Length ==> d<=if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]) { var m,n:=0,0; d:=if a[0] < b[0] then (b[0]-a[0]) else (a[0]-b[0]); while m<a.Length && n<b.Length { var t := if a[m] < b[n] then (b[n]-a[m]) else (a[m]-b[n]); d:=if t<d then t else d; if case a[m]<=b[n] => m:=m+1; case b[n]<=a[m] => n:=n+1; } }
method CanyonSearch(a: array<int>, b: array<int>) returns (d:nat) requires a.Length !=0 && b.Length!=0 requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j] requires forall i,j :: 0<=i<j<b.Length ==> b[i]<=b[j] ensures exists i,j:: 0<=i<a.Length && 0<=j<b.Length && d==if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]) ensures forall i,j:: 0<=i<a.Length && 0<=j<b.Length ==> d<=if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]) { var m,n:=0,0; d:=if a[0] < b[0] then (b[0]-a[0]) else (a[0]-b[0]); while m<a.Length && n<b.Length invariant 0<=m<=a.Length && 0<=n<=b.Length decreases a.Length -m+b.Length-n invariant exists i,j:: 0<=i<a.Length && 0<=j<b.Length && d==if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]) invariant forall i,j:: 0<=i<a.Length && 0<=j<b.Length ==> d<=(if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]))|| (m<=i&&n<=j) { var t := if a[m] < b[n] then (b[n]-a[m]) else (a[m]-b[n]); d:=if t<d then t else d; if case a[m]<=b[n] => m:=m+1; case b[n]<=a[m] => n:=n+1; } }
Clover_canyon_search.dfy
036
036
Dafny program: 036
method copy( src: array<int>, sStart: nat, dest: array<int>, dStart: nat, len: nat) returns (r: array<int>) requires src.Length >= sStart + len requires dest.Length >= dStart + len ensures r.Length == dest.Length ensures r[..dStart] == dest[..dStart] ensures r[dStart + len..] == dest[dStart + len..] ensures r[dStart..len+dStart] == src[sStart..len+sStart] { if len == 0 { return dest; } var i: nat := 0; r := new int[dest.Length]; while (i < r.Length) { r[i] := dest[i]; i := i + 1; } i := 0; while (i < len) { r[dStart + i] := src[sStart + i]; i := i + 1; } }
method copy( src: array<int>, sStart: nat, dest: array<int>, dStart: nat, len: nat) returns (r: array<int>) requires src.Length >= sStart + len requires dest.Length >= dStart + len ensures r.Length == dest.Length ensures r[..dStart] == dest[..dStart] ensures r[dStart + len..] == dest[dStart + len..] ensures r[dStart..len+dStart] == src[sStart..len+sStart] { if len == 0 { return dest; } var i: nat := 0; r := new int[dest.Length]; while (i < r.Length) invariant i <= r.Length invariant r[..i] == dest[..i] { r[i] := dest[i]; i := i + 1; } assert r[..]==dest[..]; i := 0; while (i < len) invariant i <= len invariant r[..dStart] == dest[..dStart] invariant r[(dStart + len)..] == dest[(dStart + len)..] invariant r[dStart .. dStart + i] == src[sStart .. sStart + i] { assert r[(dStart + len)..] == dest[(dStart + len)..]; r[dStart + i] := src[sStart + i]; i := i + 1; } }
Clover_copy_part.dfy
037
037
Dafny program: 037
method CountLessThan(numbers: set<int>, threshold: int) returns (count: int) ensures count == |set i | i in numbers && i < threshold| { count := 0; var shrink := numbers; var grow := {}; while |shrink | > 0 { var i: int :| i in shrink; shrink := shrink - {i}; var grow' := grow+{i}; grow := grow + {i}; if i < threshold { count := count + 1; } } }
method CountLessThan(numbers: set<int>, threshold: int) returns (count: int) ensures count == |set i | i in numbers && i < threshold| { count := 0; var shrink := numbers; var grow := {}; while |shrink | > 0 decreases shrink invariant shrink + grow == numbers invariant grow !! shrink invariant count == |set i | i in grow && i < threshold| { var i: int :| i in shrink; shrink := shrink - {i}; var grow' := grow+{i}; assert (set i | i in grow' && i < threshold) == (set i | i in grow && i < threshold )+ if i < threshold then {i} else {}; grow := grow + {i}; if i < threshold { count := count + 1; } } }
Clover_count_lessthan.dfy
038
038
Dafny program: 038
method double_array_elements(s: array<int>) modifies s ensures forall i :: 0 <= i < s.Length ==> s[i] == 2 * old(s[i]) { var i:= 0; while (i < s.Length) { s[i] := 2 * s[i]; i := i + 1; } }
method double_array_elements(s: array<int>) modifies s ensures forall i :: 0 <= i < s.Length ==> s[i] == 2 * old(s[i]) { var i:= 0; while (i < s.Length) invariant 0 <= i <= s.Length invariant forall x :: i <= x < s.Length ==> s[x] == old(s[x]) invariant forall x :: 0 <= x < i ==> s[x] == 2 * old(s[x]) { s[i] := 2 * s[i]; i := i + 1; } }
Clover_double_array_elements.dfy
040
040
Dafny program: 040
method FindEvenNumbers (arr: array<int>) returns (evenNumbers: array<int>) ensures forall x {:trigger (x%2) }:: x in arr[..] && (x%2==0)==> x in evenNumbers[..] ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..] ensures forall k :: 0 <= k < evenNumbers.Length ==> evenNumbers[k] % 2 == 0 ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==> exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m] { var evenList: seq<int> := []; ghost var indices: seq<int> := []; for i := 0 to arr.Length { if arr[i]%2==0 { evenList := evenList + [arr[i]]; indices := indices + [i]; } } evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]); }
method FindEvenNumbers (arr: array<int>) returns (evenNumbers: array<int>) ensures forall x {:trigger (x%2) }:: x in arr[..] && (x%2==0)==> x in evenNumbers[..] ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..] ensures forall k :: 0 <= k < evenNumbers.Length ==> evenNumbers[k] % 2 == 0 ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==> exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m] { var evenList: seq<int> := []; ghost var indices: seq<int> := []; for i := 0 to arr.Length invariant 0 <= i <= arr.Length invariant 0 <= |evenList| <= i invariant forall x {:trigger (x%2) }:: (x in arr[..i] && (x%2==0) )==> x in evenList[..] invariant forall k :: 0 <= k < |evenList| ==> evenList[k] % 2 == 0 invariant forall x :: x !in arr[..i] ==> x !in evenList invariant |evenList| == |indices| invariant forall k :: 0 <= k < |indices| ==> indices[k] < i invariant forall k, l :: 0 <= k < l < |indices| ==> indices[k] < indices[l] invariant forall k :: 0 <= k < |evenList| ==> 0 <= indices[k] < i <= arr.Length && arr[indices[k]] == evenList[k] { if arr[i]%2==0 { evenList := evenList + [arr[i]]; indices := indices + [i]; } } evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]); assert evenList == evenNumbers[..]; }
Clover_even_list.dfy
041
041
Dafny program: 041
method Find(a: array<int>, key: int) returns (index: int) ensures -1<=index<a.Length ensures index!=-1 ==> a[index]==key && (forall i :: 0 <= i < index ==> a[i] != key) ensures index == -1 ==> (forall i::0 <= i < a.Length ==> a[i] != key) { index := 0; while index < a.Length { if a[index] == key { return; } index := index + 1; } if index >= a.Length { index := -1; } }
method Find(a: array<int>, key: int) returns (index: int) ensures -1<=index<a.Length ensures index!=-1 ==> a[index]==key && (forall i :: 0 <= i < index ==> a[i] != key) ensures index == -1 ==> (forall i::0 <= i < a.Length ==> a[i] != key) { index := 0; while index < a.Length invariant 0<=index<=a.Length invariant (forall i::0 <= i < index==>a[i] != key) { if a[index] == key { return; } index := index + 1; } if index >= a.Length { index := -1; } }
Clover_find.dfy
042
042
Dafny program: 042
method has_close_elements(numbers: seq<real>, threshold: real) returns (res: bool) requires threshold >= 0.0 ensures res ==> exists i: int, j: int :: 0 <= i < |numbers| && 0 <= j < |numbers| && i != j && (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) < threshold ensures !res ==> (forall i: int, j: int :: 1 <= i < |numbers| && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold) { res := false; var idx: int := 0; while idx < |numbers| && !res { var idx2: int := 0; while idx2 < idx && !res { var distance := (if numbers[idx2] - numbers[idx] < 0.0 then numbers[idx] - numbers[idx2] else numbers[idx2] - numbers[idx]); if distance < threshold { res := true; return; } idx2 := idx2 + 1; } idx := idx + 1; } }
method has_close_elements(numbers: seq<real>, threshold: real) returns (res: bool) requires threshold >= 0.0 ensures res ==> exists i: int, j: int :: 0 <= i < |numbers| && 0 <= j < |numbers| && i != j && (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) < threshold ensures !res ==> (forall i: int, j: int :: 1 <= i < |numbers| && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold) { res := false; var idx: int := 0; while idx < |numbers| && !res invariant 0 <= idx <= |numbers| invariant !res invariant forall i: int, j: int :: 0 <= i < idx && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold { var idx2: int := 0; while idx2 < idx && !res invariant 0 <= idx <= |numbers| invariant 0 <= idx2 <= idx invariant !res invariant forall j: int :: 0 <= j < idx2 ==> (if numbers[idx] - numbers[j] < 0.0 then numbers[j] - numbers[idx] else numbers[idx] - numbers[j]) >= threshold { var distance := (if numbers[idx2] - numbers[idx] < 0.0 then numbers[idx] - numbers[idx2] else numbers[idx2] - numbers[idx]); if distance < threshold { res := true; return; } idx2 := idx2 + 1; } idx := idx + 1; } }
Clover_has_close_elements.dfy
043
043
Dafny program: 043
method insert(line:array<char>, l:int, nl:array<char>, p:int, at:int) requires 0 <= l+p <= line.Length requires 0 <= p <= nl.Length requires 0 <= at <= l modifies line ensures forall i :: (0<=i<p) ==> line[at+i] == nl[i] ensures forall i :: (0<=i<at) ==> line[i] == old(line[i]) ensures forall i :: (at+p<=i<l+p) ==> line[i] == old(line[i-p]) { ghost var initialLine := line[..]; var i:int := l; while(i>at) { i := i - 1; line[i+p] := line[i]; } i := 0; while(i<p) { line[at + i] := nl[i]; i := i + 1; } }
method insert(line:array<char>, l:int, nl:array<char>, p:int, at:int) requires 0 <= l+p <= line.Length requires 0 <= p <= nl.Length requires 0 <= at <= l modifies line ensures forall i :: (0<=i<p) ==> line[at+i] == nl[i] ensures forall i :: (0<=i<at) ==> line[i] == old(line[i]) ensures forall i :: (at+p<=i<l+p) ==> line[i] == old(line[i-p]) { ghost var initialLine := line[..]; var i:int := l; while(i>at) invariant line[0..i] == initialLine[0..i] invariant line[i+p..l+p] == initialLine[i..l] invariant at<=i<=l { i := i - 1; line[i+p] := line[i]; } assert line[0..at] == initialLine[0..at]; assert line[at+p..l+p] == initialLine[at..l]; i := 0; while(i<p) invariant 0<=i<=p invariant line[0..at] == initialLine[0..at] invariant line[at..at+i] == nl[0..i] invariant line[at+p..l+p] == initialLine[at..l] { line[at + i] := nl[i]; i := i + 1; } assert line[0..at] == initialLine[0..at]; assert line[at..at+p] == nl[0..p]; assert line[at+p..l+p] == initialLine[at..l]; }
Clover_insert.dfy
044
044
Dafny program: 044
method SquareRoot(N:nat) returns (r:nat) ensures r*r <= N < (r+1)*(r+1) { r:=0; while (r+1)*(r+1)<=N { r:=r+1; } }
method SquareRoot(N:nat) returns (r:nat) ensures r*r <= N < (r+1)*(r+1) { r:=0; while (r+1)*(r+1)<=N invariant r*r<=N { r:=r+1; } }
Clover_integer_square_root.dfy
046
046
Dafny program: 046
method IsPalindrome(x: seq<char>) returns (result: bool) ensures result <==> (forall i :: 0 <= i < |x| ==> x[i] == x[|x| - i - 1]) { if |x|==0 { return true; } var i := 0; var j := |x| - 1; result := true; while (i < j) { if x[i] != x[j] { result := false; return; } i := i + 1; j := j - 1; } }
method IsPalindrome(x: seq<char>) returns (result: bool) ensures result <==> (forall i :: 0 <= i < |x| ==> x[i] == x[|x| - i - 1]) { if |x|==0 { return true; } var i := 0; var j := |x| - 1; result := true; while (i < j) invariant 0<=i<=j+1 && 0<=j < |x| invariant i+j==|x|-1 invariant (forall k :: 0 <= k < i ==> x[k] == x[|x| - k - 1]) { if x[i] != x[j] { result := false; return; } i := i + 1; j := j - 1; } }
Clover_is_palindrome.dfy
047
047
Dafny program: 047
method LinearSearch(a: array<int>, e: int) returns (n:int) ensures 0<=n<=a.Length ensures n==a.Length || a[n]==e ensures forall i::0<=i < n ==> e!=a[i] { n :=0; while n!=a.Length { if e==a[n]{ return; } n:=n+1; } }
method LinearSearch(a: array<int>, e: int) returns (n:int) ensures 0<=n<=a.Length ensures n==a.Length || a[n]==e ensures forall i::0<=i < n ==> e!=a[i] { n :=0; while n!=a.Length invariant 0<=n<=a.Length invariant forall i::0<=i<n ==> e!=a[i] { if e==a[n]{ return; } n:=n+1; } }
Clover_linear_search1.dfy
048
048
Dafny program: 048
method LinearSearch(a: array<int>, e: int) returns (n:int) requires exists i::0<=i<a.Length && a[i]==e ensures 0<=n<a.Length && a[n]==e ensures forall k :: 0 <= k < n ==> a[k]!=e { n :=0; while n!=a.Length { if e==a[n]{ return; } n:=n+1; } }
method LinearSearch(a: array<int>, e: int) returns (n:int) requires exists i::0<=i<a.Length && a[i]==e ensures 0<=n<a.Length && a[n]==e ensures forall k :: 0 <= k < n ==> a[k]!=e { n :=0; while n!=a.Length invariant 0<=n<=a.Length invariant forall i::0<=i<n ==> e!=a[i] { if e==a[n]{ return; } n:=n+1; } }
Clover_linear_search2.dfy
049
049
Dafny program: 049
method LinearSearch3<T>(a: array<T>, P: T -> bool) returns (n: int) requires exists i :: 0 <= i < a.Length && P(a[i]) ensures 0 <= n < a.Length && P(a[n]) ensures forall k :: 0 <= k < n ==> !P(a[k]) { n := 0; while true { if P(a[n]) { return; } n := n + 1; } }
method LinearSearch3<T>(a: array<T>, P: T -> bool) returns (n: int) requires exists i :: 0 <= i < a.Length && P(a[i]) ensures 0 <= n < a.Length && P(a[n]) ensures forall k :: 0 <= k < n ==> !P(a[k]) { n := 0; while true invariant 0 <= n < a.Length invariant exists i :: n <= i < a.Length && P(a[i]) invariant forall k :: 0 <= k < n ==> !P(a[k]) decreases a.Length - n { if P(a[n]) { return; } n := n + 1; } }
Clover_linear_search3.dfy
050
050
Dafny program: 050
method LongestCommonPrefix(str1: seq<char>, str2: seq<char>) returns (prefix: seq<char>) ensures |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|] ensures |prefix|==|str1| || |prefix|==|str2| || (str1[|prefix|]!=str2[|prefix|]) { prefix := []; var minLength := if |str1| <|str2| then |str1| else |str2|; for idx:= 0 to minLength { if str1[idx] != str2[idx] { return; } prefix := prefix + [str1[idx]]; } }
method LongestCommonPrefix(str1: seq<char>, str2: seq<char>) returns (prefix: seq<char>) ensures |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|] ensures |prefix|==|str1| || |prefix|==|str2| || (str1[|prefix|]!=str2[|prefix|]) { prefix := []; var minLength := if |str1| <|str2| then |str1| else |str2|; for idx:= 0 to minLength invariant |prefix|==idx <= minLength<=|str1| && minLength<=|str2| invariant |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|] { if str1[idx] != str2[idx] { return; } prefix := prefix + [str1[idx]]; } }
Clover_longest_prefix.dfy
051
051
Dafny program: 051
method Match(s: string, p: string) returns (b: bool) requires |s| == |p| ensures b <==> forall n :: 0 <= n < |s| ==> s[n] == p[n] || p[n] == '?' { var i := 0; while i < |s| { if s[i] != p[i] && p[i] != '?' { return false; } i := i + 1; } return true; }
method Match(s: string, p: string) returns (b: bool) requires |s| == |p| ensures b <==> forall n :: 0 <= n < |s| ==> s[n] == p[n] || p[n] == '?' { var i := 0; while i < |s| invariant 0 <= i <= |s| invariant forall n :: 0 <= n < i ==> s[n] == p[n] || p[n] == '?' { if s[i] != p[i] && p[i] != '?' { return false; } i := i + 1; } return true; }
Clover_match.dfy
052
052
Dafny program: 052
method maxArray(a: array<int>) returns (m: int) requires a.Length >= 1 ensures forall k :: 0 <= k < a.Length ==> m >= a[k] ensures exists k :: 0 <= k < a.Length && m == a[k] { m := a[0]; var index := 1; while (index < a.Length) { m := if m>a[index] then m else a[index]; index := index + 1; } }
method maxArray(a: array<int>) returns (m: int) requires a.Length >= 1 ensures forall k :: 0 <= k < a.Length ==> m >= a[k] ensures exists k :: 0 <= k < a.Length && m == a[k] { m := a[0]; var index := 1; while (index < a.Length) invariant 0 <= index <= a.Length invariant forall k :: 0 <= k < index ==> m >= a[k] invariant exists k :: 0 <= k < index && m == a[k] decreases a.Length - index { m := if m>a[index] then m else a[index]; index := index + 1; } }
Clover_max_array.dfy
053
053
Dafny program: 053
method minArray(a: array<int>) returns (r:int) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> r <= a[i] ensures exists i :: 0 <= i < a.Length && r == a[i] { r:=a[0]; var i:=1; while i<a.Length { if r>a[i]{ r:=a[i]; } i:=i+1; } }
method minArray(a: array<int>) returns (r:int) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> r <= a[i] ensures exists i :: 0 <= i < a.Length && r == a[i] { r:=a[0]; var i:=1; while i<a.Length invariant 0 <= i <= a.Length invariant forall x :: 0 <= x < i ==> r <= a[x] invariant exists x :: 0 <= x < i && r == a[x] { if r>a[i]{ r:=a[i]; } i:=i+1; } }
Clover_min_array.dfy
057
057
Dafny program: 057
method onlineMax(a: array<int>, x: int) returns (ghost m:int, p:int) requires 1<=x<a.Length requires a.Length!=0 ensures x<=p<a.Length ensures forall i::0<=i<x==> a[i]<=m ensures exists i::0<=i<x && a[i]==m ensures x<=p<a.Length-1 ==> (forall i::0<=i<p ==> a[i]<a[p]) ensures (forall i::x<=i<a.Length && a[i]<=m) ==> p==a.Length-1 { p:= 0; var best := a[0]; var i:=1; while i<x { if a[i]>best{ best:=a[i]; } i:=i+1; } m:=best; i:=x; while i<a.Length { if a[i]>best{ p:=i; return; } i:=i+1; } p:=a.Length-1; }
method onlineMax(a: array<int>, x: int) returns (ghost m:int, p:int) requires 1<=x<a.Length requires a.Length!=0 ensures x<=p<a.Length ensures forall i::0<=i<x==> a[i]<=m ensures exists i::0<=i<x && a[i]==m ensures x<=p<a.Length-1 ==> (forall i::0<=i<p ==> a[i]<a[p]) ensures (forall i::x<=i<a.Length && a[i]<=m) ==> p==a.Length-1 { p:= 0; var best := a[0]; var i:=1; while i<x invariant 0<=i<=x invariant forall j::0<=j<i==> a[j]<=best invariant exists j::0<=j<i && a[j]==best { if a[i]>best{ best:=a[i]; } i:=i+1; } m:=best; i:=x; while i<a.Length invariant x<=i<=a.Length invariant forall j::x<=j<i ==> a[j]<=m { if a[i]>best{ p:=i; return; } i:=i+1; } p:=a.Length-1; }
Clover_online_max.dfy
058
058
Dafny program: 058
method only_once<T(==)>(a: array<T>, key: T) returns (b:bool) ensures (multiset(a[..])[key] ==1 ) <==> b { var i := 0; b := false; var keyCount := 0; while i < a.Length { if (a[i] == key) { keyCount := keyCount + 1; } if (keyCount == 1) { b := true; } else { b := false; } i := i + 1; } }
method only_once<T(==)>(a: array<T>, key: T) returns (b:bool) ensures (multiset(a[..])[key] ==1 ) <==> b { var i := 0; b := false; var keyCount := 0; while i < a.Length invariant 0 <= i <= a.Length invariant multiset(a[..i])[key] == keyCount invariant b <==> (keyCount == 1) { if (a[i] == key) { keyCount := keyCount + 1; } if (keyCount == 1) { b := true; } else { b := false; } i := i + 1; } assert a[..a.Length] == a[..]; }
Clover_only_once.dfy
059
059
Dafny program: 059
method Quotient(x: nat, y:nat) returns (r:int, q:int) requires y != 0 ensures q * y + r == x && 0 <= r < y && 0 <= q { r:=x; q:=0; while y<=r { r:=r-y; q:=q+1; } }
method Quotient(x: nat, y:nat) returns (r:int, q:int) requires y != 0 ensures q * y + r == x && 0 <= r < y && 0 <= q { r:=x; q:=0; while y<=r invariant q*y+r==x && r>=0 decreases r { r:=r-y; q:=q+1; } }
Clover_quotient.dfy
060
060
Dafny program: 060
method remove_front(a:array<int>) returns (c:array<int>) requires a.Length>0 ensures a[1..] == c[..] { c := new int[a.Length-1]; var i:= 1; while (i < a.Length) { c[i-1] := a[i]; i:=i+1; } }
method remove_front(a:array<int>) returns (c:array<int>) requires a.Length>0 ensures a[1..] == c[..] { c := new int[a.Length-1]; var i:= 1; while (i < a.Length) invariant 1 <= i <= a.Length invariant forall ii::1<=ii<i ==> c[ii-1]==a[ii] { c[i-1] := a[i]; i:=i+1; } }
Clover_remove_front.dfy
061
061
Dafny program: 061
method replace(arr: array<int>, k: int) modifies arr ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) > k ==> arr[i] == -1 ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) <= k ==> arr[i] == old(arr[i]) { var i := 0; while i < arr.Length { if arr[i] > k { arr[i] := -1; } i := i + 1; } }
method replace(arr: array<int>, k: int) modifies arr ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) > k ==> arr[i] == -1 ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) <= k ==> arr[i] == old(arr[i]) { var i := 0; while i < arr.Length decreases arr.Length - i invariant 0 <= i <= arr.Length invariant forall j :: 0 <= j < i ==> old(arr[j]) > k ==> arr[j] == -1 invariant forall j :: 0 <= j < i ==> old(arr[j]) <= k ==> arr[j] == old(arr[j]) invariant forall j :: i <= j < arr.Length ==> old(arr[j]) == arr[j] { if arr[i] > k { arr[i] := -1; } i := i + 1; } }
Clover_replace.dfy
063
063
Dafny program: 063
method reverse(a: array<int>) modifies a ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[a.Length - 1 - i]) { var i := 0; while i <a.Length / 2 { a[i], a[a.Length-1-i] := a[a.Length-1-i], a[i]; i := i + 1; } }
method reverse(a: array<int>) modifies a ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[a.Length - 1 - i]) { var i := 0; while i <a.Length / 2 invariant 0 <= i <= a.Length/2 invariant forall k :: 0 <= k < i || a.Length-1-i < k <= a.Length-1 ==> a[k] == old(a[a.Length-1-k]) invariant forall k :: i <= k <= a.Length-1-i ==> a[k] == old(a[k]) { a[i], a[a.Length-1-i] := a[a.Length-1-i], a[i]; i := i + 1; } }
Clover_reverse.dfy
064
064
Dafny program: 064
method rotate(a: array<int>, offset:int) returns (b: array<int> ) requires 0<=offset ensures b.Length==a.Length ensures forall i::0<=i<a.Length ==> b[i]==a[(i+offset)%a.Length] { b:= new int[a.Length]; var i:=0; while i<a.Length { b[i]:=a[(i+offset)%a.Length]; i:=i+1; } }
method rotate(a: array<int>, offset:int) returns (b: array<int> ) requires 0<=offset ensures b.Length==a.Length ensures forall i::0<=i<a.Length ==> b[i]==a[(i+offset)%a.Length] { b:= new int[a.Length]; var i:=0; while i<a.Length invariant 0<=i<=a.Length invariant forall j ::0<=j<i ==> b[j]==a[(j+offset)%a.Length] { b[i]:=a[(i+offset)%a.Length]; i:=i+1; } }
Clover_rotate.dfy
065
065
Dafny program: 065
method SelectionSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { var n:= 0; while n != a.Length { var mindex, m := n, n+1; while m != a.Length { if a[m] < a[mindex] { mindex := m; } m := m+1; } a[n], a[mindex] := a[mindex], a[n]; n := n+1; } }
method SelectionSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { var n:= 0; while n != a.Length invariant 0 <= n <= a.Length invariant forall i, j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j] invariant forall i,j :: 0 <= i < j < n ==> a[i] <= a[j] invariant multiset(a[..]) == old(multiset(a[..])) { var mindex, m := n, n+1; while m != a.Length invariant n <= mindex < m <= a.Length invariant forall i :: n <= i < m ==> a[mindex] <= a[i] { if a[m] < a[mindex] { mindex := m; } m := m+1; } a[n], a[mindex] := a[mindex], a[n]; n := n+1; } }
Clover_selectionsort.dfy
067
067
Dafny program: 067
method SetToSeq<T>(s: set<T>) returns (xs: seq<T>) ensures multiset(s) == multiset(xs) { xs := []; var left: set<T> := s; while left != {} { var x :| x in left; left := left - {x}; xs := xs + [x]; } }
method SetToSeq<T>(s: set<T>) returns (xs: seq<T>) ensures multiset(s) == multiset(xs) { xs := []; var left: set<T> := s; while left != {} invariant multiset(left) + multiset(xs) == multiset(s) { var x :| x in left; left := left - {x}; xs := xs + [x]; } }
Clover_set_to_seq.dfy
068
068
Dafny program: 068
method SlopeSearch(a: array2<int>, key: int) returns (m:int, n:int) requires forall i,j,j'::0<=i<a.Length0 && 0<=j<j'<a.Length1 ==> a[i,j]<=a[i,j'] requires forall i,i',j::0<=i<i'<a.Length0 && 0<=j<a.Length1 ==> a[i,j]<=a[i',j] requires exists i,j :: 0<=i<a.Length0 && 0<=j<a.Length1 && a[i,j]==key ensures 0<=m<a.Length0 && 0<=n<a.Length1 ensures a[m,n]==key { m,n:=0, a.Length1-1; while a[m,n] !=key { if a[m,n] < key { m:=m+1; }else{ n:=n-1; } } }
method SlopeSearch(a: array2<int>, key: int) returns (m:int, n:int) requires forall i,j,j'::0<=i<a.Length0 && 0<=j<j'<a.Length1 ==> a[i,j]<=a[i,j'] requires forall i,i',j::0<=i<i'<a.Length0 && 0<=j<a.Length1 ==> a[i,j]<=a[i',j] requires exists i,j :: 0<=i<a.Length0 && 0<=j<a.Length1 && a[i,j]==key ensures 0<=m<a.Length0 && 0<=n<a.Length1 ensures a[m,n]==key { m,n:=0, a.Length1-1; while a[m,n] !=key invariant 0<=m<a.Length0 && 0<=n<a.Length1 invariant exists i,j :: m<=i<a.Length0 && 0<=j<=n && a[i,j]==key decreases a.Length0-m+n { if a[m,n] < key { m:=m+1; }else{ n:=n-1; } } }
Clover_slope_search.dfy
079
079
Dafny program: 079
method twoSum(nums: array<int>, target: int) returns (i: int, j: int) requires nums.Length > 1 requires exists i,j::0 <= i < j < nums.Length && nums[i] + nums[j] == target ensures 0 <= i < j < nums.Length && nums[i] + nums[j] == target ensures forall ii,jj:: (0 <= ii < i && ii < jj < nums.Length) ==> nums[ii] + nums[jj] != target ensures forall jj:: i < jj < j ==> nums[i] + nums[jj] != target { var n := nums.Length; i := 0; j := 1; while i < n - 1 { j := i + 1; while j < n { if nums[i] + nums[j] == target { return; } j := j + 1; } i := i + 1; } }
method twoSum(nums: array<int>, target: int) returns (i: int, j: int) requires nums.Length > 1 requires exists i,j::0 <= i < j < nums.Length && nums[i] + nums[j] == target ensures 0 <= i < j < nums.Length && nums[i] + nums[j] == target ensures forall ii,jj:: (0 <= ii < i && ii < jj < nums.Length) ==> nums[ii] + nums[jj] != target ensures forall jj:: i < jj < j ==> nums[i] + nums[jj] != target { var n := nums.Length; i := 0; j := 1; while i < n - 1 invariant 0 <= i < j <= n invariant forall ii, jj :: 0 <= ii < i && ii < jj < n ==> nums[ii] + nums[jj] != target { j := i + 1; while j < n invariant 0 <= i < j <= n invariant forall jj :: i < jj < j ==> nums[i] + nums[jj] != target { if nums[i] + nums[j] == target { return; } j := j + 1; } i := i + 1; } }
Clover_two_sum.dfy
082
082
Dafny program: 082
// Redo for exam function gcd(a: nat, b: nat): nat lemma r1(a: nat) ensures gcd(a, 0) == a lemma r2(a:nat) ensures gcd(a, a) == a lemma r3(a: nat, b: nat) ensures gcd(a, b) == gcd(b, a) lemma r4 (a: nat, b: nat) ensures b > 0 ==> gcd(a, b) == gcd(b, a % b) method GCD1(a: int, b: int) returns (r: int) requires a > 0 && b > 0 ensures gcd(a,b) == r { if a < b { r3(a,b); r := GCD1(b, a); } else if (a % b == 0) { r4(a,b); r1(b); r := b; } else { r4(a,b); r := GCD1(b, a % b); } } method GCD2(a: int, b: int) returns (r: int) requires a > 0 && b >= 0 ensures gcd(a,b) == r { r1(a); r4(a,b); ( b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a) ) && ( (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))) ); b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a); b == 0 ==> a > 0 && b >= 0 && gcd(a,b) == a; (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))); b >= 0 && b != 0 ==> b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)); if b == 0 { r1(a); gcd(a,b) == a; r := a; gcd(a,b) == r; } else { r4(a,b); // Method call rule b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)); // assert // gcd(a,b) == GCD2(b, a % b); r := GCD2(b, a % b); gcd(a,b) == r; } gcd(a,b) == r; }
// Redo for exam function gcd(a: nat, b: nat): nat lemma r1(a: nat) ensures gcd(a, 0) == a lemma r2(a:nat) ensures gcd(a, a) == a lemma r3(a: nat, b: nat) ensures gcd(a, b) == gcd(b, a) lemma r4 (a: nat, b: nat) ensures b > 0 ==> gcd(a, b) == gcd(b, a % b) method GCD1(a: int, b: int) returns (r: int) requires a > 0 && b > 0 ensures gcd(a,b) == r decreases b { if a < b { r3(a,b); r := GCD1(b, a); } else if (a % b == 0) { r4(a,b); assert b > 0; assert gcd(a, b) == gcd(b, a % b); assert a % b == 0; assert gcd(a, b) == gcd(b, 0); r1(b); assert gcd(a, b) == b; r := b; assert gcd(a,b) == r; } else { r4(a,b); r := GCD1(b, a % b); assert gcd(a,b) == r; } assert gcd(a,b) == r; } method GCD2(a: int, b: int) returns (r: int) requires a > 0 && b >= 0 decreases b ensures gcd(a,b) == r { r1(a); r4(a,b); assert ( b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a) ) && ( (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))) ); assert b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a); assert b == 0 ==> a > 0 && b >= 0 && gcd(a,b) == a; assert (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))); assert b >= 0 && b != 0 ==> b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)); if b == 0 { r1(a); assert gcd(a,b) == a; r := a; assert gcd(a,b) == r; } else { r4(a,b); // Method call rule assert b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)); // assert // gcd(a,b) == GCD2(b, a % b); r := GCD2(b, a % b); assert gcd(a,b) == r; } assert gcd(a,b) == r; }
Correctness_tmp_tmpwqvg5q_4_HoareLogic_exam.dfy
083
083
Dafny program: 083
/** (a) Verify whether or not the following program satisfies total correctness. You should use weakest precondition reasoning and may extend the loop invariant if required. You will need to add a decreases clause to prove termination (a) Weakest precondition proof (without termination) (6 marks) Termination proof (2marks) */ function fusc(n: int): nat lemma rule1() ensures fusc(0) == 0 lemma rule2() ensures fusc(1) == 1 lemma rule3(n:nat) ensures fusc(2*n) == fusc(n) lemma rule4(n:nat) ensures fusc(2*n+1) == fusc(n) + fusc(n+1) method ComputeFusc(N: int) returns (b: int) requires N >= 0 ensures b == fusc(N) { b := 0; var n, a := N, 1; while (n != 0) { ghost var d := n; // termination metric if (n % 2 == 0) { rule4(n/2); rule3(n/2); a := a + b; n := n / 2; } else { rule4((n-1)/2); rule3((n-1)/2); rule3((n+1)/2); b * fusc(n) - b * fusc(n) + b * fusc(((n-1)/2)+1) + a * fusc(n); b * fusc(n) - b * (fusc(n) - fusc(((n-1)/2)+1)) + a * fusc(n); a * fusc(n - 1) + b * fusc(n) - b * fusc(n-1) + a * fusc(n) - a * fusc(n-1); b := b + a; n := (n - 1) / 2; } } rule1(); rule2(); }
/** (a) Verify whether or not the following program satisfies total correctness. You should use weakest precondition reasoning and may extend the loop invariant if required. You will need to add a decreases clause to prove termination (a) Weakest precondition proof (without termination) (6 marks) Termination proof (2marks) */ function fusc(n: int): nat lemma rule1() ensures fusc(0) == 0 lemma rule2() ensures fusc(1) == 1 lemma rule3(n:nat) ensures fusc(2*n) == fusc(n) lemma rule4(n:nat) ensures fusc(2*n+1) == fusc(n) + fusc(n+1) method ComputeFusc(N: int) returns (b: int) requires N >= 0 ensures b == fusc(N) { b := 0; var n, a := N, 1; assert 0 <= n <= N; assert fusc(N) == a * fusc(n) + b * fusc(n + 1); while (n != 0) invariant 0 <= n <= N // J invariant fusc(N) == a * fusc(n) + b * fusc(n + 1) // J decreases n // D { ghost var d := n; // termination metric assert fusc(N) == a * fusc(n) + b * fusc(n + 1); assert n != 0; assert (n % 2 != 0 && n % 2 == 0) || fusc(N) == a * fusc(n) + b * fusc(n + 1); assert (n % 2 != 0 || n % 2 == 0) ==> fusc(N) == a * fusc(n) + b * fusc(n + 1); assert n % 2 != 0 || fusc(N) == a * fusc(n) + b * fusc(n + 1); assert n % 2 == 0 || fusc(N) == a * fusc(n) + b * fusc(n + 1); assert n % 2 == 0 ==> fusc(N) == a * fusc(n) + b * fusc(n + 1); assert n % 2 != 0 ==> fusc(N) == a * fusc(n) + b * fusc(n + 1); if (n % 2 == 0) { rule4(n/2); assert fusc((n/2) + 1) == fusc(n + 1) - fusc(n/2); rule3(n/2); assert fusc(n/2) == fusc(n); assert fusc(N) == (a + b) * fusc(n/2) + b * fusc((n/2) + 1); a := a + b; assert fusc(N) == a * fusc(n/2) + b * fusc((n/2) + 1); n := n / 2; assert fusc(N) == a * fusc(n) + b * fusc(n + 1); } else { rule4((n-1)/2); assert fusc(n) - fusc((n-1)/2) == fusc(((n-1)/2)+1); rule3((n-1)/2); assert fusc((n-1)/2) == fusc(n-1); assert fusc(((n-1)/2)+1) == fusc((n+1)/2); rule3((n+1)/2); assert fusc((n+1)/2) == fusc(n+1); assert fusc(N) == a * fusc(n) + b * fusc(n + 1); assert fusc(N) == b * fusc(((n-1)/2)+1) + a * fusc(n); assert fusc(N) == b * fusc(n) - b * fusc(n) + b * fusc(((n-1)/2)+1) + a * fusc(n); assert fusc(N) == b * fusc(n) - b * (fusc(n) - fusc(((n-1)/2)+1)) + a * fusc(n); assert fusc(N) == b * fusc(n) - b * fusc((n-1)/2) + a * fusc(n); assert fusc(N) == b * fusc(n) - b * fusc(n-1) + a * fusc(n); assert fusc(N) == b * fusc(n) - b * fusc(n-1) + a * fusc(n); assert fusc(N) == a * fusc(n - 1) + b * fusc(n) - b * fusc(n-1) + a * fusc(n) - a * fusc(n-1); assert fusc(N) == a * fusc(n - 1) + (b + a) * (fusc(n) - fusc(n-1)); assert fusc(N) == a * fusc((n - 1)) + (b + a) * (fusc(n) - fusc((n-1)/2)); assert fusc(N) == a * fusc((n - 1) / 2) + (b + a) * fusc(((n - 1) / 2) + 1); b := b + a; assert fusc(N) == a * fusc((n - 1) / 2) + b * fusc(((n - 1) / 2) + 1); n := (n - 1) / 2; assert fusc(N) == a * fusc(n) + b * fusc(n + 1); } assert n < d; // termination metric assert fusc(N) == a * fusc(n) + b * fusc(n + 1); // J } assert n == 0; // !B rule1(); assert fusc(0) == 0; rule2(); assert fusc(1) == 1; assert fusc(N) == a * fusc(0) + b * fusc(0 + 1); // J assert fusc(N) == a * 0 + b * 1; // J assert b == fusc(N); }
Correctness_tmp_tmpwqvg5q_4_MethodCalls_q1.dfy
084
084
Dafny program: 084
/** Ather, Mohammad Faiz (s4648481/3) CSSE3100 Assignemnt 3 The University of Queensland */ // Question 1 method Tangent(r: array<int>, x: array<int>) returns (found: bool) requires forall i:: 1 <= i < x.Length ==> x[i-1] < x[i] requires forall i, j :: 0 <= i < j < x.Length ==> x[i] < x[j] ensures !found ==> forall i,j :: 0 <= i < r.Length && 0 <= j < x.Length ==> r[i] != x[j] ensures found ==> exists i,j :: 0 <= i < r.Length && 0 <= j < x.Length && r[i] == x[j] { found := false; var n, f := 0, x.Length; while n != r.Length && !found forall i,j :: 0 <= i < n && 0 <= j < x.Length ==> r[i] != x[j] exists i,j :: 0 <= i < r.Length && 0 <= j < x.Length && n == i && f == j && r[i] == x[j] { f := BinarySearch(x, r[n]); /* not iterate over either array once a tangent has been found */ // see if if (f != x.Length && r[n] == x[f]) { found := true; } else { n := n + 1; } } (!found && n == r.Length) || ( found && n != r.Length && r[n] == x[f]); !false; // sanity check } // Author: Leino, Title: Program Proofs method BinarySearch(a: array<int>, circle: int) returns (n: int) requires forall i :: 1 <= i < a.Length ==> a[i-1] < a[i] requires forall i, j :: 0 <= i < j < a.Length ==> a[i] < a[j] ensures 0 <= n <= a.Length ensures forall i :: 0 <= i < n ==> a[i] < circle ensures forall i :: n <= i < a.Length ==> circle <= a[i] { var lo, hi := 0, a.Length; while lo < hi 0 <= i < lo ==> a[i] < circle hi <= i < a.Length ==> a[i] >= circle { var mid := (lo + hi) / 2; calc { lo; == (lo + lo) / 2; <= { assert lo <= hi; } (lo + hi) / 2; < { assert lo < hi; } (hi + hi) / 2; == hi; } /* for a given circle in r, should not iterate over array x once it can be deduced that no tangent will be found for that circle. */ // see if and 1st else if if (a[lo] > circle) { hi := lo; } else if (a[hi-1] < circle) { lo := hi; } else if (a[mid] < circle) { lo := mid + 1; } else { hi := mid; } } n := lo; !false; // sanity check }
/** Ather, Mohammad Faiz (s4648481/3) CSSE3100 Assignemnt 3 The University of Queensland */ // Question 1 method Tangent(r: array<int>, x: array<int>) returns (found: bool) requires forall i:: 1 <= i < x.Length ==> x[i-1] < x[i] requires forall i, j :: 0 <= i < j < x.Length ==> x[i] < x[j] ensures !found ==> forall i,j :: 0 <= i < r.Length && 0 <= j < x.Length ==> r[i] != x[j] ensures found ==> exists i,j :: 0 <= i < r.Length && 0 <= j < x.Length && r[i] == x[j] { found := false; var n, f := 0, x.Length; while n != r.Length && !found invariant 0 <= n <= r.Length invariant !found ==> forall i,j :: 0 <= i < n && 0 <= j < x.Length ==> r[i] != x[j] invariant found ==> exists i,j :: 0 <= i < r.Length && 0 <= j < x.Length && n == i && f == j && r[i] == x[j] decreases r.Length - n, !found { f := BinarySearch(x, r[n]); /* not iterate over either array once a tangent has been found */ // see if if (f != x.Length && r[n] == x[f]) { found := true; } else { n := n + 1; } } assert (!found && n == r.Length) || ( found && n != r.Length && r[n] == x[f]); assert !false; // sanity check } // Author: Leino, Title: Program Proofs method BinarySearch(a: array<int>, circle: int) returns (n: int) requires forall i :: 1 <= i < a.Length ==> a[i-1] < a[i] requires forall i, j :: 0 <= i < j < a.Length ==> a[i] < a[j] ensures 0 <= n <= a.Length ensures forall i :: 0 <= i < n ==> a[i] < circle ensures forall i :: n <= i < a.Length ==> circle <= a[i] { var lo, hi := 0, a.Length; while lo < hi invariant 0 <= lo <= hi <= a.Length invariant forall i :: 0 <= i < lo ==> a[i] < circle invariant forall i :: hi <= i < a.Length ==> a[i] >= circle decreases hi - lo { var mid := (lo + hi) / 2; calc { lo; == (lo + lo) / 2; <= { assert lo <= hi; } (lo + hi) / 2; < { assert lo < hi; } (hi + hi) / 2; == hi; } /* for a given circle in r, should not iterate over array x once it can be deduced that no tangent will be found for that circle. */ // see if and 1st else if if (a[lo] > circle) { hi := lo; } else if (a[hi-1] < circle) { lo := hi; } else if (a[mid] < circle) { lo := mid + 1; } else { hi := mid; } } n := lo; assert !false; // sanity check }
Correctness_tmp_tmpwqvg5q_4_Sorting_Tangent.dfy
085
085
Dafny program: 085
//Method barrier below receives an array and an integer p //and returns a boolean b which is true if and only if //all the positions to the left of p and including also position p contain elements //that are strictly smaller than all the elements contained in the positions to the right of p //Examples: // If v=[7,2,5,8] and p=0 or p=1 then the method must return false, // but for p=2 the method should return true //1.Specify the method //2.Implement an O(v.size()) method //3.Verify the method method barrier(v:array<int>,p:int) returns (b:bool) //Give the precondition //Give the postcondition //{Implement and verify} requires v.Length > 0 requires 0<=p<v.Length ensures b==forall k,l::0<=k<=p && p<l<v.Length ==> v[k]<v[l] { var i:=1; var max:=0; while(i<=p) { if(v[i]>v[max]){ max:=i; } i:=i+1; } while(i<v.Length && v[i]>v[max]) { i:=i+1; } b:=i==v.Length; }
//Method barrier below receives an array and an integer p //and returns a boolean b which is true if and only if //all the positions to the left of p and including also position p contain elements //that are strictly smaller than all the elements contained in the positions to the right of p //Examples: // If v=[7,2,5,8] and p=0 or p=1 then the method must return false, // but for p=2 the method should return true //1.Specify the method //2.Implement an O(v.size()) method //3.Verify the method method barrier(v:array<int>,p:int) returns (b:bool) //Give the precondition //Give the postcondition //{Implement and verify} requires v.Length > 0 requires 0<=p<v.Length ensures b==forall k,l::0<=k<=p && p<l<v.Length ==> v[k]<v[l] { var i:=1; var max:=0; while(i<=p) decreases p-i invariant 0<=i<=p+1 invariant 0<=max<i invariant forall k::0<=k<i ==> v[max] >= v[k] { if(v[i]>v[max]){ max:=i; } i:=i+1; } while(i<v.Length && v[i]>v[max]) decreases v.Length - i invariant 0<=i<=v.Length invariant forall k::0<=k<=p ==> v[k]<=v[max] invariant forall k::p<k<i ==> v[k] > v[max] { i:=i+1; } b:=i==v.Length; }
Dafny-Exercises_tmp_tmpjm75muf__Session10Exercises_ExerciseBarrier.dfy
087
087
Dafny program: 087
function fib(n: nat): nat { if n == 0 then 0 else if n == 1 then 1 else fib(n - 1) + fib(n - 2) } method fibonacci1(n:nat) returns (f:nat) ensures f==fib(n) { var i := 0; f := 0; var fsig := 1; while i < n { f, fsig := fsig, f + fsig; i := i + 1; } } method fibonacci2(n:nat) returns (f:nat) ensures f==fib(n) { if (n==0) {f:=0;} else{ var i := 1; var fant := 0; f := 1; while i < n { fant, f := f, fant + f; i := i + 1; } } } method fibonacci3(n:nat) returns (f:nat) ensures f==fib(n) { { var i: int := 0; var a := 1; f := 0; while i < n else a==fib(i-1) && f==fib(i) { a, f := f, a + f; i := i + 1; } } }
function fib(n: nat): nat decreases n { if n == 0 then 0 else if n == 1 then 1 else fib(n - 1) + fib(n - 2) } method fibonacci1(n:nat) returns (f:nat) ensures f==fib(n) { var i := 0; f := 0; var fsig := 1; while i < n decreases n - i//write the bound invariant f==fib(i) && fsig==fib(i+1)//write the invariant invariant i<=n { f, fsig := fsig, f + fsig; i := i + 1; } } method fibonacci2(n:nat) returns (f:nat) ensures f==fib(n) { if (n==0) {f:=0;} else{ var i := 1; var fant := 0; f := 1; while i < n decreases n-i//write the bound invariant fant==fib(i-1) && f==fib(i)//write the invariant invariant i<=n { fant, f := f, fant + f; i := i + 1; } } } method fibonacci3(n:nat) returns (f:nat) ensures f==fib(n) { { var i: int := 0; var a := 1; f := 0; while i < n decreases n-i//write the bound invariant 0<=i<=n invariant if i ==0 then a==fib(i+1) && f==fib(i)//write the invariant else a==fib(i-1) && f==fib(i) { a, f := f, a + f; i := i + 1; } } }
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseFibonacci.dfy
088
088
Dafny program: 088
predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} method mpositive(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=0; //1. assert positive(v[..0]) while i<v.Length && v[i]>=0 { //2. assert 0<=i<v.Length && positive(v[..i]); i:=i+1; //2. assert 0<=i<v.Length && positive(v[..i]); } //3. assert i==v.Length ==> positive(v[..]); //3. assert i<v.Length => v[i]<0; b := i==v.Length; } method mpositive3(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=0; b:=true; while(i<v.Length && b) { b:=v[i]>=0; i:=i+1; } } method mpositive4(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=0; b:=true; while(i<v.Length && b) { b:=v[i]>=0; i:=i+1; } } method mpositivertl(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=v.Length-1; while(i>=0 && v[i]>=0) { i:=i-1; } b:= i==-1; }
predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} method mpositive(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=0; //1. assert positive(v[..0]) while i<v.Length && v[i]>=0 decreases v.Length - i invariant 0<=i<=v.Length invariant positive(v[..i]) { //2. assert 0<=i<v.Length && positive(v[..i]); i:=i+1; //2. assert 0<=i<v.Length && positive(v[..i]); } //3. assert i==v.Length ==> positive(v[..]); //3. assert i<v.Length => v[i]<0; b := i==v.Length; } method mpositive3(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=0; b:=true; while(i<v.Length && b) decreases v.Length - i invariant 0 <= i <= v.Length invariant b==positive(v[0..i]) invariant !b ==> !positive(v[0..v.Length]) { b:=v[i]>=0; i:=i+1; } } method mpositive4(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=0; b:=true; while(i<v.Length && b) decreases v.Length - i invariant 0 <= i <= v.Length invariant b==positive(v[0..i]) invariant !b ==> !positive(v[0..v.Length]) { b:=v[i]>=0; i:=i+1; } } method mpositivertl(v:array<int>) returns (b:bool) ensures b==positive(v[0..v.Length]) { var i:=v.Length-1; while(i>=0 && v[i]>=0) decreases i invariant -1 <= i < v.Length invariant positive(v[i+1..]) { i:=i-1; } b:= i==-1; }
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExercisePositive.dfy
089
089
Dafny program: 089
method mroot1(n:int) returns (r:int) //Cost O(root n) requires n>=0 ensures r>=0 && r*r <= n <(r+1)*(r+1) { r:=0; while (r+1)*(r+1) <=n { r:=r+1; } } method mroot2(n:int) returns (r:int) //Cost O(n) requires n>=0 ensures r>=0 && r*r <= n <(r+1)*(r+1) { r:=n; while n<r*r { r:=r-1; } } method mroot3(n:int) returns (r:int) //Cost O(log n) requires n>=0 ensures r>=0 && r*r <= n <(r+1)*(r+1) { var y:int; var h:int; r:=0; y:=n+1; //Search in interval [0,n+1) while (y!=r+1) //[r,y] { h:=(r+y)/2; if (h*h<=n) {r:=h;} else {y:=h;} } }
method mroot1(n:int) returns (r:int) //Cost O(root n) requires n>=0 ensures r>=0 && r*r <= n <(r+1)*(r+1) { r:=0; while (r+1)*(r+1) <=n invariant r>=0 && r*r <=n decreases n-r*r { r:=r+1; } } method mroot2(n:int) returns (r:int) //Cost O(n) requires n>=0 ensures r>=0 && r*r <= n <(r+1)*(r+1) { r:=n; while n<r*r invariant 0<=r<=n && n<(r+1)*(r+1)//write the invariant invariant r*r<=n ==> n<(r+1)*(r+1) decreases r//write the bound { r:=r-1; } } method mroot3(n:int) returns (r:int) //Cost O(log n) requires n>=0 ensures r>=0 && r*r <= n <(r+1)*(r+1) { var y:int; var h:int; r:=0; y:=n+1; //Search in interval [0,n+1) while (y!=r+1) //[r,y] invariant r>=0 && r*r<=n<y*y && y>=r+1// write the invariant decreases y-r//write the bound { h:=(r+y)/2; if (h*h<=n) {r:=h;} else {y:=h;} } }
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseSquare_root.dfy
090
090
Dafny program: 090
//Algorithm 1: From left to right return the first method mmaximum1(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] { var j:=1; i:=0; while(j<v.Length) { if(v[j] > v[i]){i:=j;} j:=j+1; } } //Algorithm 2: From right to left return the last method mmaximum2(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] { var j:=v.Length-2; i:=v.Length - 1; while(j>=0) { if(v[j] > v[i]){i:=j;} j:=j-1; } } method mfirstMaximum(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] ensures forall l:: 0<=l<i ==> v[i]>v[l] //Algorithm: from left to right { var j:=1; i:=0; while(j<v.Length) { if(v[j] > v[i]){i:=j;} j:=j+1; } } method mlastMaximum(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] ensures forall l:: i<l<v.Length ==> v[i]>v[l] { var j:=v.Length-2; i := v.Length-1; while(j>=0) { if(v[j] > v[i]){i:=j;} j:=j-1; } } //Algorithm : from left to right //Algorithm : from right to left method mmaxvalue1(v:array<int>) returns (m:int) requires v.Length>0 ensures m in v[..] ensures forall k::0<=k<v.Length ==> m>=v[k] { var i:=mmaximum1(v); m:=v[i]; } method mmaxvalue2(v:array<int>) returns (m:int) requires v.Length>0 ensures m in v[..] ensures forall k::0<=k<v.Length ==> m>=v[k] { var i:=mmaximum2(v); m:=v[i]; }
//Algorithm 1: From left to right return the first method mmaximum1(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] { var j:=1; i:=0; while(j<v.Length) decreases v.Length - j invariant 0<=j<=v.Length invariant 0<=i<j invariant forall k:: 0<=k<j ==> v[i] >= v[k] { if(v[j] > v[i]){i:=j;} j:=j+1; } } //Algorithm 2: From right to left return the last method mmaximum2(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] { var j:=v.Length-2; i:=v.Length - 1; while(j>=0) decreases j invariant 0<=i<v.Length invariant -1<=j<v.Length-1 invariant forall k :: v.Length>k>j ==> v[k]<=v[i] { if(v[j] > v[i]){i:=j;} j:=j-1; } } method mfirstMaximum(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] ensures forall l:: 0<=l<i ==> v[i]>v[l] //Algorithm: from left to right { var j:=1; i:=0; while(j<v.Length) decreases v.Length - j invariant 0<=j<=v.Length invariant 0<=i<j invariant forall k:: 0<=k<j ==> v[i] >= v[k] invariant forall k:: 0<=k<i ==> v[i] > v[k] { if(v[j] > v[i]){i:=j;} j:=j+1; } } method mlastMaximum(v:array<int>) returns (i:int) requires v.Length>0 ensures 0<=i<v.Length ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k] ensures forall l:: i<l<v.Length ==> v[i]>v[l] { var j:=v.Length-2; i := v.Length-1; while(j>=0) decreases j invariant -1<=j<v.Length-1 invariant 0<=i<v.Length invariant forall k :: v.Length>k>j ==> v[k]<=v[i] invariant forall k :: v.Length>k>i ==> v[k]<v[i] { if(v[j] > v[i]){i:=j;} j:=j-1; } } //Algorithm : from left to right //Algorithm : from right to left method mmaxvalue1(v:array<int>) returns (m:int) requires v.Length>0 ensures m in v[..] ensures forall k::0<=k<v.Length ==> m>=v[k] { var i:=mmaximum1(v); m:=v[i]; } method mmaxvalue2(v:array<int>) returns (m:int) requires v.Length>0 ensures m in v[..] ensures forall k::0<=k<v.Length ==> m>=v[k] { var i:=mmaximum2(v); m:=v[i]; }
Dafny-Exercises_tmp_tmpjm75muf__Session3Exercises_ExerciseMaximum.dfy
091
091
Dafny program: 091
predicate allEqual(s:seq<int>) {forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] } //{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] } //{forall i::0<i<|s| ==> s[i-1]==s[i]} //{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]} //Ordered indexes lemma equivalenceNoOrder(s:seq<int>) ensures allEqual(s) <==> forall i,j::0<=i<=j<|s| ==> s[i]==s[j] {} //All equal to first lemma equivalenceEqualtoFirst(s:seq<int>) requires s!=[] ensures allEqual(s) <==> (forall i::0<=i<|s| ==> s[0]==s[i]) {} lemma equivalenceContiguous(s:seq<int>) ensures (allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1]) ensures (allEqual(s) <== forall i::0<=i<|s|-1 ==> s[i]==s[i+1]) { if(|s|==0 || |s|==1){ } else{ calc { forall i::0<=i<|s|-1 ==> s[i]==s[i+1]; ==> { equivalenceContiguous(s[..|s|-1]); } allEqual(s); } } } method mallEqual1(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i := 0; b := true; while (i < v.Length && b) { b:=(v[i]==v[0]); i := i+1; } } method mallEqual2(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i:int; b:=true; i:=0; while (i < v.Length && v[i] == v[0]) { i:=i+1; } b:=(i==v.Length); } method mallEqual3(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { equivalenceContiguous(v[..]); var i:int; b:=true; if (v.Length >0){ i:=0; while (i<v.Length-1 && v[i]==v[i+1]) { i:=i+1; } b:=(i==v.Length-1); } } method mallEqual4(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i:int; b:=true; if (v.Length>0){ i:=0; while (i < v.Length-1 && b) { b:=(v[i]==v[i+1]); i:=i+1; } } } method mallEqual5(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i := 0; b := true; while (i < v.Length && b) { if (v[i] != v[0]) { b := false; } else { i := i+1;} } }
predicate allEqual(s:seq<int>) {forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] } //{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] } //{forall i::0<i<|s| ==> s[i-1]==s[i]} //{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]} //Ordered indexes lemma equivalenceNoOrder(s:seq<int>) ensures allEqual(s) <==> forall i,j::0<=i<=j<|s| ==> s[i]==s[j] {} //All equal to first lemma equivalenceEqualtoFirst(s:seq<int>) requires s!=[] ensures allEqual(s) <==> (forall i::0<=i<|s| ==> s[0]==s[i]) {} lemma equivalenceContiguous(s:seq<int>) ensures (allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1]) ensures (allEqual(s) <== forall i::0<=i<|s|-1 ==> s[i]==s[i+1]) { assert allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1]; if(|s|==0 || |s|==1){ } else{ calc { forall i::0<=i<|s|-1 ==> s[i]==s[i+1]; ==> { equivalenceContiguous(s[..|s|-1]); assert s[|s|-2] == s[|s|-1]; } allEqual(s); } } } method mallEqual1(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i := 0; b := true; while (i < v.Length && b) invariant 0 <= i <= v.Length invariant b==allEqual(v[..i]) decreases v.Length - i { b:=(v[i]==v[0]); i := i+1; } } method mallEqual2(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i:int; b:=true; i:=0; while (i < v.Length && v[i] == v[0]) invariant 0 <= i <= v.Length invariant forall k:: 0 <= k < i ==> v[k] == v[0] decreases v.Length - i { i:=i+1; } b:=(i==v.Length); } method mallEqual3(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { equivalenceContiguous(v[..]); var i:int; b:=true; if (v.Length >0){ i:=0; while (i<v.Length-1 && v[i]==v[i+1]) invariant 0<=i<=v.Length -1 invariant b==allEqual(v[..i+1]) decreases v.Length - i { i:=i+1; } b:=(i==v.Length-1); } } method mallEqual4(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i:int; b:=true; if (v.Length>0){ i:=0; while (i < v.Length-1 && b) invariant 0 <= i < v.Length invariant b==allEqual(v[..i+1]) decreases v.Length - i { b:=(v[i]==v[i+1]); i:=i+1; } } } method mallEqual5(v:array<int>) returns (b:bool) ensures b==allEqual(v[0..v.Length]) { var i := 0; b := true; while (i < v.Length && b) invariant 0<=i<=v.Length// invariant b ==> forall k::0<=k<i ==> v[k] == v[0] invariant !b ==> exists k:: 0<=k<v.Length && v[k]!=v[0] decreases v.Length - i - (if b then 0 else 1)// { if (v[i] != v[0]) { b := false; } else { i := i+1;} } }
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseAllEqual.dfy
092
092
Dafny program: 092
predicate strictSorted(s : seq<int>) { forall u, w :: 0 <= u < w < |s| ==> s[u] < s[w] } method mcontained(v:array<int>,w:array<int>,n:int,m:int) returns (b:bool) //Specify and implement an O(m+n) algorithm that returns b //v and w are strictly increasing ordered arrays //b is true iff the first n elements of v are contained in the first m elements of w requires n<=m && n>=0 requires strictSorted(v[..]) requires strictSorted(w[..]) requires v.Length >= n && w.Length >= m ensures b==forall k:: 0<= k< n ==> v[k] in w[..m]//exists j :: 0 <= j < m && v[k] == w[j] { var i:=0; var j:=0; while(i<n && j<m && (v[i] >= w[j])) //&& b) { if(v[i] == w[j]){ i:=i+1; } j:=j+1; } b := i==n; }
predicate strictSorted(s : seq<int>) { forall u, w :: 0 <= u < w < |s| ==> s[u] < s[w] } method mcontained(v:array<int>,w:array<int>,n:int,m:int) returns (b:bool) //Specify and implement an O(m+n) algorithm that returns b //v and w are strictly increasing ordered arrays //b is true iff the first n elements of v are contained in the first m elements of w requires n<=m && n>=0 requires strictSorted(v[..]) requires strictSorted(w[..]) requires v.Length >= n && w.Length >= m ensures b==forall k:: 0<= k< n ==> v[k] in w[..m]//exists j :: 0 <= j < m && v[k] == w[j] { var i:=0; var j:=0; while(i<n && j<m && (v[i] >= w[j])) //&& b) invariant 0<=i<=n invariant 0<=j<=m invariant strictSorted(v[..]) invariant strictSorted(w[..]) invariant forall k::0<=k<i ==> v[k] in w[..j] invariant i<n ==> !(v[i] in w[..j]) decreases w.Length-j decreases v.Length-i { if(v[i] == w[j]){ i:=i+1; } j:=j+1; } assert i<n ==> !(v[i] in w[..m]); b := i==n; }
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseContained.dfy
093
093
Dafny program: 093
predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} method mfirstNegative(v:array<int>) returns (b:bool, i:int) ensures b <==> exists k::0<=k<v.Length && v[k]<0 ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i]) { i:=0; b:=false; while (i<v.Length && !b) { b:=(v[i]<0); i:=i+1; } if (b){i:=i-1;} } method mfirstNegative2(v:array<int>) returns (b:bool, i:int) ensures b <==> exists k::0<=k<v.Length && v[k]<0 ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i]) { i:=0;b:=false; while (i<v.Length && !b) { b:=(v[i]<0); if (!b) {i:=i+1;} } }
predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} method mfirstNegative(v:array<int>) returns (b:bool, i:int) ensures b <==> exists k::0<=k<v.Length && v[k]<0 ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i]) { i:=0; b:=false; while (i<v.Length && !b) invariant 0<=i<=v.Length invariant b <==> exists k::0<=k<i && v[k]<0 invariant b ==> v[i-1]<0 && positive(v[0..i-1]) decreases v.Length - i { b:=(v[i]<0); i:=i+1; } if (b){i:=i-1;} } method mfirstNegative2(v:array<int>) returns (b:bool, i:int) ensures b <==> exists k::0<=k<v.Length && v[k]<0 ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i]) { i:=0;b:=false; while (i<v.Length && !b) invariant 0<=i<=v.Length invariant b ==> i<v.Length && v[i]<0 && !(exists k::0<=k<i && v[k]<0) invariant b <== exists k::0<=k<i && v[k]<0 decreases v.Length - i - (if b then 1 else 0) { b:=(v[i]<0); if (!b) {i:=i+1;} } }
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseFirstNegative.dfy
094
094
Dafny program: 094
method mfirstCero(v:array<int>) returns (i:int) ensures 0 <=i<=v.Length ensures forall j:: 0<=j<i ==> v[j]!=0 ensures i!=v.Length ==> v[i]==0 { i:=0; while (i<v.Length && v[i]!=0) {i:=i+1;} }
method mfirstCero(v:array<int>) returns (i:int) ensures 0 <=i<=v.Length ensures forall j:: 0<=j<i ==> v[j]!=0 ensures i!=v.Length ==> v[i]==0 { i:=0; while (i<v.Length && v[i]!=0) invariant 0<=i<=v.Length invariant forall j:: 0<=j<i ==> v[j]!=0 decreases v.Length -i {i:=i+1;} }
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExercisefirstZero.dfy
095
095
Dafny program: 095
function SumR(s:seq<int>):int { if (s==[]) then 0 else SumR(s[..|s|-1])+s[|s|-1] } function SumL(s:seq<int>):int { if (s==[]) then 0 else s[0]+SumL(s[1..]) } lemma concatLast(s:seq<int>,t:seq<int>) requires t!=[] ensures (s+t)[..|s+t|-1] == s+(t[..|t|-1]) {} lemma concatFirst(s:seq<int>,t:seq<int>) requires s!=[] ensures (s+t)[1..] == s[1..]+t {} lemma {:induction s,t} SumByPartsR(s:seq<int>,t:seq<int>) ensures SumR(s+t) == SumR(s)+SumR(t) { if (t==[]) {assert s+t == s;} else if (s==[]) {assert s+t==t;} else { calc =={ SumR(s+t); SumR((s+t)[..|s+t|-1])+(s+t)[|s+t|-1]; SumR((s+t)[..|s+t|-1])+t[|t|-1]; {concatLast(s,t);} SumR(s+t[..|t|-1])+t[|t|-1]; {SumByPartsR(s,t[..|t|-1]);} SumR(s)+SumR(t[..|t|-1])+t[|t|-1]; SumR(s)+SumR(t); } } } lemma {:induction s,t} SumByPartsL(s:seq<int>,t:seq<int>) ensures SumL(s+t) == SumL(s)+SumL(t) //Prove this { if(t==[]){ } else if(s==[]){ } else{ calc == { SumL(s+t); (s+t)[0] + SumL((s+t)[1..]); s[0] + SumL((s+t)[1..]); {concatFirst(s,t);} s[0] + SumL(s[1..] + t); {SumByPartsL(s[1..], t);} s[0] + SumL(s[1..]) + SumL(t); } } } lemma {:induction s,i,j} equalSumR(s:seq<int>,i:int,j:int) requires 0<=i<=j<=|s| ensures SumR(s[i..j])==SumL(s[i..j]) //Prove this { if(s==[]){ }else{ if(i==j){ } else{ calc == { SumR(s[i..j]); { } SumR(s[i..j-1]) + s[j-1]; {equalSumR(s, i, j-1);} SumL(s[i..j-1]) + s[j-1]; {assert s[j-1] == SumL([s[j-1]]);} SumL(s[i..j-1]) + SumL([s[j-1]]); {SumByPartsL(s[i..j-1], [s[j-1]]);} SumL(s[i..j-1] + [s[j-1]]); { } SumL(s[i..j]); /*SumR(s[i..j-1])+SumR(s[j..j]); SumR(s[i..j-1]) + s[j..j]; SumL(s);*/ } } } } lemma equalSumsV() ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j]) //proving the forall { forall v:array<int>,i,j | 0<=i<=j<=v.Length ensures SumR(v[i..j])==SumL(v[i..j]) {equalSumR(v[..],i,j);} } function SumV(v:array<int>,c:int,f:int):int requires 0<=c<=f<=v.Length reads v {SumR(v[c..f])} lemma ArrayFacts<T>() ensures forall v : array<T> :: v[..v.Length] == v[..]; ensures forall v : array<T> :: v[0..] == v[..]; ensures forall v : array<T> :: v[0..v.Length] == v[..]; ensures forall v : array<T> ::|v[0..v.Length]|==v.Length; ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1; ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k] // ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j]) {equalSumsV();} method sumElems(v:array<int>) returns (sum:int) //ensures sum==SumL(v[0..v.Length]) ensures sum==SumR(v[..]) //ensures sum==SumV(v,0,v.Length) {ArrayFacts<int>(); sum:=0; var i:int; i:=0; while (i<v.Length) { sum:=sum+v[i]; i:=i+1; } } method sumElemsB(v:array<int>) returns (sum:int) //ensures sum==SumL(v[0..v.Length]) ensures sum==SumR(v[0..v.Length]) { ArrayFacts<int>(); sum:=0; var i:int; i:=v.Length; equalSumsV(); while(i>0) { sum:=sum+v[i-1]; i:=i-1; } }
function SumR(s:seq<int>):int decreases s { if (s==[]) then 0 else SumR(s[..|s|-1])+s[|s|-1] } function SumL(s:seq<int>):int decreases s { if (s==[]) then 0 else s[0]+SumL(s[1..]) } lemma concatLast(s:seq<int>,t:seq<int>) requires t!=[] ensures (s+t)[..|s+t|-1] == s+(t[..|t|-1]) {} lemma concatFirst(s:seq<int>,t:seq<int>) requires s!=[] ensures (s+t)[1..] == s[1..]+t {} lemma {:induction s,t} SumByPartsR(s:seq<int>,t:seq<int>) decreases s,t ensures SumR(s+t) == SumR(s)+SumR(t) { if (t==[]) {assert s+t == s;} else if (s==[]) {assert s+t==t;} else { calc =={ SumR(s+t); SumR((s+t)[..|s+t|-1])+(s+t)[|s+t|-1]; SumR((s+t)[..|s+t|-1])+t[|t|-1]; {concatLast(s,t);} SumR(s+t[..|t|-1])+t[|t|-1]; {SumByPartsR(s,t[..|t|-1]);} SumR(s)+SumR(t[..|t|-1])+t[|t|-1]; SumR(s)+SumR(t); } } } lemma {:induction s,t} SumByPartsL(s:seq<int>,t:seq<int>) decreases s,t ensures SumL(s+t) == SumL(s)+SumL(t) //Prove this { if(t==[]){ assert s+t==s; } else if(s==[]){ assert s+t==t; } else{ calc == { SumL(s+t); (s+t)[0] + SumL((s+t)[1..]); s[0] + SumL((s+t)[1..]); {concatFirst(s,t);} s[0] + SumL(s[1..] + t); {SumByPartsL(s[1..], t);} s[0] + SumL(s[1..]) + SumL(t); } } } lemma {:induction s,i,j} equalSumR(s:seq<int>,i:int,j:int) decreases j-i requires 0<=i<=j<=|s| ensures SumR(s[i..j])==SumL(s[i..j]) //Prove this { if(s==[]){ assert SumR(s) == SumL(s); }else{ if(i==j){ assert SumR(s[i..j]) == SumL(s[i..j]); } else{ calc == { SumR(s[i..j]); { assert s[i..j] == s[i..j-1] + [s[j-1]]; assert SumR(s[i..j]) == SumR(s[i..j-1]) + s[j-1]; } SumR(s[i..j-1]) + s[j-1]; {equalSumR(s, i, j-1);} SumL(s[i..j-1]) + s[j-1]; {assert s[j-1] == SumL([s[j-1]]);} SumL(s[i..j-1]) + SumL([s[j-1]]); {SumByPartsL(s[i..j-1], [s[j-1]]);} SumL(s[i..j-1] + [s[j-1]]); { assert s[i..j] == s[i..j-1] + [s[j-1]]; } SumL(s[i..j]); /*SumR(s[i..j-1])+SumR(s[j..j]); SumR(s[i..j-1]) + s[j..j]; SumL(s);*/ } } } } lemma equalSumsV() ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j]) //proving the forall { forall v:array<int>,i,j | 0<=i<=j<=v.Length ensures SumR(v[i..j])==SumL(v[i..j]) {equalSumR(v[..],i,j);} } function SumV(v:array<int>,c:int,f:int):int requires 0<=c<=f<=v.Length reads v {SumR(v[c..f])} lemma ArrayFacts<T>() ensures forall v : array<T> :: v[..v.Length] == v[..]; ensures forall v : array<T> :: v[0..] == v[..]; ensures forall v : array<T> :: v[0..v.Length] == v[..]; ensures forall v : array<T> ::|v[0..v.Length]|==v.Length; ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1; ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k] // ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j]) {equalSumsV();} method sumElems(v:array<int>) returns (sum:int) //ensures sum==SumL(v[0..v.Length]) ensures sum==SumR(v[..]) //ensures sum==SumV(v,0,v.Length) {ArrayFacts<int>(); sum:=0; var i:int; i:=0; while (i<v.Length) decreases v.Length - i//write invariant 0<=i<=v.Length && sum == SumR(v[..i])//write { sum:=sum+v[i]; i:=i+1; } } method sumElemsB(v:array<int>) returns (sum:int) //ensures sum==SumL(v[0..v.Length]) ensures sum==SumR(v[0..v.Length]) { ArrayFacts<int>(); sum:=0; var i:int; i:=v.Length; equalSumsV(); while(i>0) decreases i//write invariant 0<=i<=v.Length invariant sum == SumL(v[i..]) == SumR(v[i..]) { sum:=sum+v[i-1]; i:=i-1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session5Exercises_ExerciseSumElems.dfy
096
096
Dafny program: 096
predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} predicate isEven(i:int) requires i>=0 {i%2==0} function CountEven(s:seq<int>):int requires positive(s) {if s==[] then 0 else (if (s[|s|-1]%2==0) then 1 else 0)+CountEven(s[..|s|-1]) } lemma ArrayFacts<T>() ensures forall v : array<T> :: v[..v.Length] == v[..]; ensures forall v : array<T> :: v[0..] == v[..]; ensures forall v : array<T> :: v[0..v.Length] == v[..]; ensures forall v : array<T> ::|v[0..v.Length]|==v.Length; ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1; ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k] {} method mcountEven(v:array<int>) returns (n:int) requires positive(v[..]) ensures n==CountEven(v[..]) { ArrayFacts<int>(); n:=0; var i:int; i:=0; while (i<v.Length) { if (v[i]%2==0) {n:=n+1;} i:=i+1; } }
predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} predicate isEven(i:int) requires i>=0 {i%2==0} function CountEven(s:seq<int>):int decreases s requires positive(s) {if s==[] then 0 else (if (s[|s|-1]%2==0) then 1 else 0)+CountEven(s[..|s|-1]) } lemma ArrayFacts<T>() ensures forall v : array<T> :: v[..v.Length] == v[..]; ensures forall v : array<T> :: v[0..] == v[..]; ensures forall v : array<T> :: v[0..v.Length] == v[..]; ensures forall v : array<T> ::|v[0..v.Length]|==v.Length; ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1; ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k] {} method mcountEven(v:array<int>) returns (n:int) requires positive(v[..]) ensures n==CountEven(v[..]) { ArrayFacts<int>(); n:=0; var i:int; i:=0; while (i<v.Length) decreases v.Length - i//write invariant 0<=i<=v.Length//write invariant n==CountEven(v[..i]) { if (v[i]%2==0) {n:=n+1;} i:=i+1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExerciseCountEven.dfy
097
097
Dafny program: 097
function min(v:array<int>,i:int):int reads v requires 1<=i<=v.Length ensures forall k::0<=k<i==> v[k]>=min(v,i) {if (i==1) then v[0] else if (v[i-1]<=min(v,i-1)) then v[i-1] else min(v,i-1) } function countMin(v:array<int>,x:int, i:int):int reads v requires 0<=i<=v.Length ensures !(x in v[0..i]) ==> countMin(v,x,i)==0 { if (i==0) then 0 else if (v[i-1]==x) then 1+countMin(v,x,i-1) else countMin(v,x,i-1) } method mCountMin(v:array<int>) returns (c:int) requires v.Length>0 ensures c==countMin(v,min(v,v.Length),v.Length) //Implement and verify an O(v.Length) algorithm { var i:=1; c:=1; var mini:=v[0]; while(i<v.Length) { if(v[i]==mini){ c:=c + 1; } else if(v[i]<mini){ c:=1; mini:=v[i]; } i:=i+1; } }
function min(v:array<int>,i:int):int decreases i reads v requires 1<=i<=v.Length ensures forall k::0<=k<i==> v[k]>=min(v,i) {if (i==1) then v[0] else if (v[i-1]<=min(v,i-1)) then v[i-1] else min(v,i-1) } function countMin(v:array<int>,x:int, i:int):int decreases i reads v requires 0<=i<=v.Length ensures !(x in v[0..i]) ==> countMin(v,x,i)==0 { if (i==0) then 0 else if (v[i-1]==x) then 1+countMin(v,x,i-1) else countMin(v,x,i-1) } method mCountMin(v:array<int>) returns (c:int) requires v.Length>0 ensures c==countMin(v,min(v,v.Length),v.Length) //Implement and verify an O(v.Length) algorithm { var i:=1; c:=1; var mini:=v[0]; while(i<v.Length) decreases v.Length -i invariant 0<i<=v.Length invariant mini==min(v,i) invariant c==countMin(v, mini, i) { if(v[i]==mini){ c:=c + 1; } else if(v[i]<mini){ c:=1; mini:=v[i]; } i:=i+1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExerciseCountMin.dfy
098
098
Dafny program: 098
predicate isPeek(v:array<int>,i:int) reads v requires 0<=i<v.Length {forall k::0<=k<i ==> v[i]>=v[k]} function peekSum(v:array<int>,i:int):int reads v requires 0<=i<=v.Length { if (i==0) then 0 else if isPeek(v,i-1) then v[i-1]+peekSum(v,i-1) else peekSum(v,i-1) } method mPeekSum(v:array<int>) returns (sum:int) requires v.Length>0 ensures sum==peekSum(v,v.Length) //Implement and verify an O(v.Length) algorithm to solve this problem { var i:=1; sum:=v[0]; var lmax:=v[0]; while(i<v.Length) { if(v[i]>=lmax){ sum:=sum + v[i]; lmax:=v[i]; } i:=i+1; } }
predicate isPeek(v:array<int>,i:int) reads v requires 0<=i<v.Length {forall k::0<=k<i ==> v[i]>=v[k]} function peekSum(v:array<int>,i:int):int decreases i reads v requires 0<=i<=v.Length { if (i==0) then 0 else if isPeek(v,i-1) then v[i-1]+peekSum(v,i-1) else peekSum(v,i-1) } method mPeekSum(v:array<int>) returns (sum:int) requires v.Length>0 ensures sum==peekSum(v,v.Length) //Implement and verify an O(v.Length) algorithm to solve this problem { var i:=1; sum:=v[0]; var lmax:=v[0]; while(i<v.Length) decreases v.Length -i invariant 0<i<=v.Length invariant lmax in v[..i] invariant forall k::0<=k<i ==> lmax>=v[k]; invariant sum==peekSum(v, i) { if(v[i]>=lmax){ sum:=sum + v[i]; lmax:=v[i]; } i:=i+1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExercisePeekSum.dfy
099
099
Dafny program: 099
predicate sorted(s : seq<int>) { forall u, w :: 0 <= u < w < |s| ==> s[u] <= s[w] } method binarySearch(v:array<int>, elem:int) returns (p:int) requires sorted(v[0..v.Length]) ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { var c,f:=0,v.Length-1; while (c<=f) (forall w::f<w<v.Length ==> v[w]>elem) { var m:=(c+f)/2; if (v[m]<=elem) {c:=m+1;} else {f:=m-1;} } p:=c-1; } method search(v:array<int>,elem:int) returns (b:bool) requires sorted(v[0..v.Length]) ensures b==(elem in v[0..v.Length]) //Implement by calling binary search function { var p:=binarySearch(v, elem); if(p==-1){ b:= false; } else{ b:=v[p] == elem; } } //Recursive binary search method {:tailrecursion false} binarySearchRec(v:array<int>, elem:int, c:int, f:int) returns (p:int) requires sorted(v[0..v.Length]) requires 0<=c<=f+1<=v.Length//0<=c<=v.Length && -1<=f<v.Length && c<=f+1 requires forall k::0<=k<c ==> v[k]<=elem requires forall k::f<k<v.Length ==> v[k]>elem ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { if (c==f+1) {p:=c-1;} //empty case: c-1 contains the last element less or equal than elem else { var m:=(c+f)/2; if (v[m]<=elem) {p:=binarySearchRec(v,elem,m+1,f);} else {p:=binarySearchRec(v,elem,c,m-1);} } } method otherbSearch(v:array<int>, elem:int) returns (b:bool,p:int) requires sorted(v[0..v.Length]) ensures 0<=p<=v.Length ensures b == (elem in v[0..v.Length]) ensures b ==> p<v.Length && v[p]==elem ensures !b ==> (forall u::0<=u<p ==> v[u]<elem) && (forall w::p<=w<v.Length ==> v[w]>elem) //Implement and verify { p:=binarySearch(v, elem); if(p==-1){ b:= false; p:=p+1; } else{ b:=v[p] == elem; p:=p + if b then 0 else 1; } }
predicate sorted(s : seq<int>) { forall u, w :: 0 <= u < w < |s| ==> s[u] <= s[w] } method binarySearch(v:array<int>, elem:int) returns (p:int) requires sorted(v[0..v.Length]) ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { var c,f:=0,v.Length-1; while (c<=f) decreases f-c invariant 0<=c<=v.Length && -1<=f<=v.Length-1 && c<=f+1 invariant (forall u::0<=u<c ==> v[u]<=elem) && (forall w::f<w<v.Length ==> v[w]>elem) { var m:=(c+f)/2; if (v[m]<=elem) {c:=m+1;} else {f:=m-1;} } p:=c-1; } method search(v:array<int>,elem:int) returns (b:bool) requires sorted(v[0..v.Length]) ensures b==(elem in v[0..v.Length]) //Implement by calling binary search function { var p:=binarySearch(v, elem); if(p==-1){ b:= false; } else{ b:=v[p] == elem; } } //Recursive binary search method {:tailrecursion false} binarySearchRec(v:array<int>, elem:int, c:int, f:int) returns (p:int) requires sorted(v[0..v.Length]) requires 0<=c<=f+1<=v.Length//0<=c<=v.Length && -1<=f<v.Length && c<=f+1 requires forall k::0<=k<c ==> v[k]<=elem requires forall k::f<k<v.Length ==> v[k]>elem decreases f-c ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { if (c==f+1) {p:=c-1;} //empty case: c-1 contains the last element less or equal than elem else { var m:=(c+f)/2; if (v[m]<=elem) {p:=binarySearchRec(v,elem,m+1,f);} else {p:=binarySearchRec(v,elem,c,m-1);} } } method otherbSearch(v:array<int>, elem:int) returns (b:bool,p:int) requires sorted(v[0..v.Length]) ensures 0<=p<=v.Length ensures b == (elem in v[0..v.Length]) ensures b ==> p<v.Length && v[p]==elem ensures !b ==> (forall u::0<=u<p ==> v[u]<elem) && (forall w::p<=w<v.Length ==> v[w]>elem) //Implement and verify { p:=binarySearch(v, elem); if(p==-1){ b:= false; p:=p+1; } else{ b:=v[p] == elem; p:=p + if b then 0 else 1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBinarySearch.dfy
100
100
Dafny program: 100
predicate sorted_seg(a:array<int>, i:int, j:int) //j excluded requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method bubbleSorta(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; while (i< f) { var j:=f-1; while (j > i) { //assert a[j] //assert multiset(a[c..f]) == old(multiset(a[c..f])) ; if (a[j-1]>a[j]){ a[j],a[j-1]:=a[j-1],a[j]; } j:=j-1; } i:=i+1; } } method bubbleSort(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; var b:=true; while (i<f && b) { var j:=f-1; b:=false; while (j>i) { if (a[j-1]>a[j]) { a[j],a[j-1]:=a[j-1],a[j]; b:=true; } j:=j-1; } i:=i+1; } }
predicate sorted_seg(a:array<int>, i:int, j:int) //j excluded requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method bubbleSorta(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; while (i< f) decreases a.Length-i invariant c<=i<=f invariant sorted_seg(a,c,i) invariant forall k,l::c<=k< i && i<=l< f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var j:=f-1; assert multiset(a[c..f]) == old(multiset(a[c..f])) ; while (j > i) decreases j-i//write invariant i <= j<= f-1//write invariant forall k::j<=k<=f-1 ==> a[j] <= a[k] invariant forall k,l::c<=k< i && i<=l< f ==> a[k]<=a[l] invariant sorted_seg(a,c,i) invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { //assert a[j] //assert multiset(a[c..f]) == old(multiset(a[c..f])) ; if (a[j-1]>a[j]){ a[j],a[j-1]:=a[j-1],a[j]; } j:=j-1; } assert sorted_seg(a,c,i+1); assert forall k::i<k<f ==> a[i]<=a[k]; i:=i+1; } } method bubbleSort(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; var b:=true; while (i<f && b) decreases a.Length-i invariant c<=i<=f invariant sorted_seg(a,c,i) invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) invariant !b ==> sorted_seg(a,i,f) { var j:=f-1; b:=false; assert multiset(a[c..f]) == old(multiset(a[c..f])) ; while (j>i) decreases j-i//write invariant i<=j<=f-1//write invariant forall k::j<=k<=f-1 ==> a[j] <= a[k] invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant sorted_seg(a,c,i) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) invariant !b ==> sorted_seg(a,j,f) invariant multiset(a[c..f]) == old(multiset(a[c..f])) { if (a[j-1]>a[j]) { a[j],a[j-1]:=a[j-1],a[j]; b:=true; } j:=j-1; } assert !b ==> sorted_seg(a,i,f); i:=i+1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBubbleSort.dfy
101
101
Dafny program: 101
method replace(v:array<int>, x:int, y:int) modifies v ensures forall k::0<=k<old(v.Length) && old(v[k])==x ==> v[k]==y ensures forall k::0<=k<old(v.Length) && old(v[k])!=x ==> v[k]==old(v[k]) { var i:=0; while(i<v.Length) { if(v[i]==x){ v[i]:=y; } i:=i+1; } }
method replace(v:array<int>, x:int, y:int) modifies v ensures forall k::0<=k<old(v.Length) && old(v[k])==x ==> v[k]==y ensures forall k::0<=k<old(v.Length) && old(v[k])!=x ==> v[k]==old(v[k]) { var i:=0; while(i<v.Length) decreases v.Length - i invariant 0<=i<=v.Length invariant forall k::0<=k<i && old(v[k])==x ==> v[k]==y invariant forall k::i<=k<v.Length ==> v[k] == old(v[k]) invariant forall k::0<=k<i && old(v[k])!=x ==> v[k]==old(v[k]) { if(v[i]==x){ v[i]:=y; } i:=i+1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseReplace.dfy
102
102
Dafny program: 102
predicate sorted_seg(a:array<int>, i:int, j:int) //j not included requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method selSort (a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) {if (c<=f-1){//two elements at least var i:=c; while (i<f-1) //outer loop { var less:=i; var j:=i+1; while (j<f) //inner loop { if (a[j]<a[less]) {less:=j;} j:=j+1; } a[i],a[less]:=a[less],a[i]; i:=i+1; } } }
predicate sorted_seg(a:array<int>, i:int, j:int) //j not included requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method selSort (a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) {if (c<=f-1){//two elements at least var i:=c; while (i<f-1) //outer loop decreases f-i invariant c<=i<=f invariant sorted_seg(a,c,i) invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var less:=i; var j:=i+1; while (j<f) //inner loop decreases f-j//write invariant i+1<=j<=f//write invariant i<=less<f invariant sorted_seg(a,c,i) invariant forall k::i<=k<j ==> a[less] <= a[k] invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { if (a[j]<a[less]) {less:=j;} j:=j+1; } a[i],a[less]:=a[less],a[i]; i:=i+1; } } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseSelSort.dfy
103
103
Dafny program: 103
predicate strictNegative(v:array<int>,i:int,j:int) reads v requires 0<=i<=j<=v.Length {forall u | i<=u<j :: v[u]<0} predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} predicate isPermutation(s:seq<int>, t:seq<int>) {multiset(s)==multiset(t)} /** returns an index st new array is a permutation of the old array positive first and then strictnegative, i is the firs neg or len if not any */ method separate(v:array<int>) returns (i:int) modifies v ensures 0<=i<=v.Length ensures positive(v[0..i]) && strictNegative(v,i,v.Length) ensures isPermutation(v[0..v.Length], old(v[0..v.Length])) { i:=0; var j:=v.Length - 1; while(i<=j) { if(v[i]>=0){ i:=i+1; } else if(v[j]>=0){ v[i],v[j]:=v[j],v[i]; j:=j-1; i:=i+1; } else if(v[j]<0){ j:=j-1; } } }
predicate strictNegative(v:array<int>,i:int,j:int) reads v requires 0<=i<=j<=v.Length {forall u | i<=u<j :: v[u]<0} predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} predicate isPermutation(s:seq<int>, t:seq<int>) {multiset(s)==multiset(t)} /** returns an index st new array is a permutation of the old array positive first and then strictnegative, i is the firs neg or len if not any */ method separate(v:array<int>) returns (i:int) modifies v ensures 0<=i<=v.Length ensures positive(v[0..i]) && strictNegative(v,i,v.Length) ensures isPermutation(v[0..v.Length], old(v[0..v.Length])) { i:=0; var j:=v.Length - 1; while(i<=j) decreases j-i invariant 0<=i<=j+1<=v.Length invariant strictNegative(v,j+1,v.Length) invariant positive(v[0..i]) invariant isPermutation(v[0..v.Length], old(v[0..v.Length])) { if(v[i]>=0){ i:=i+1; } else if(v[j]>=0){ assert v[i]<0; v[i],v[j]:=v[j],v[i]; j:=j-1; i:=i+1; } else if(v[j]<0){ j:=j-1; } } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseSeparate.dfy
104
104
Dafny program: 104
predicate sorted_seg(a:array<int>, i:int, j:int) //i and j included requires 0 <= i <= j+1 <= a.Length reads a { forall l, k :: i <= l <= k <= j ==> a[l] <= a[k] } method InsertionSort(a: array<int>) modifies a; ensures sorted_seg(a,0,a.Length-1) ensures multiset(a[..]) == old(multiset(a[..])) //Add and prove this { var i := 0; while (i < a.Length) { var temp := a[i]; var j := i; while (j > 0 && temp < a[j - 1]) { a[j] := a[j - 1]; j := j - 1; } a[j] := temp; i := i + 1; } }
predicate sorted_seg(a:array<int>, i:int, j:int) //i and j included requires 0 <= i <= j+1 <= a.Length reads a { forall l, k :: i <= l <= k <= j ==> a[l] <= a[k] } method InsertionSort(a: array<int>) modifies a; ensures sorted_seg(a,0,a.Length-1) ensures multiset(a[..]) == old(multiset(a[..])) //Add and prove this { var i := 0; assert multiset(a[..]) == old(multiset(a[..])); while (i < a.Length) decreases a.Length-i invariant 0<=i<=a.Length invariant sorted_seg(a,0,i-1) invariant multiset(a[..]) == old(multiset(a[..]))//add invariant forall k::i<k<a.Length ==> a[k] == old(a[k]) { var temp := a[i]; var j := i; while (j > 0 && temp < a[j - 1]) decreases j invariant 0<=j<=i invariant sorted_seg(a,0,j-1) && sorted_seg(a,j+1,i) invariant forall k,l :: 0<=k<=j-1 && j+1<=l<=i ==> a[k]<=a[l] invariant forall k :: j<k<=i ==> temp <a[k] invariant forall k::i<k<a.Length ==> a[k] == old(a[k]) invariant multiset(a[..]) - multiset{a[j]} + multiset{temp} == old(multiset(a[..]))//add { a[j] := a[j - 1]; j := j - 1; } a[j] := temp; i := i + 1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session8Exercises_ExerciseInsertionSort.dfy
105
105
Dafny program: 105
function Sum(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length { if (i==j) then 0 else Sum(v,i,j-1)+v[j-1] } predicate SumMaxToRight(v:array<int>,i:int,s:int) reads v requires 0<=i<v.Length { forall l,ss {:induction l}::0<=l<=i && ss==i+1==> Sum(v,l,ss)<=s } method segMaxSum(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum(v,k,i+1) && SumMaxToRight(v,i,s) { s:=v[0]; k:=0; var j:=0; while (j<i) { if (s+v[j+1]>v[j+1]) {s:=s+v[j+1];} else {k:=j+1;s:=v[j+1];} j:=j+1; } } function Sum2(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length { if (i==j) then 0 else v[i]+Sum2(v,i+1,j) } //Now do the same but with a loop from right to left predicate SumMaxToRight2(v:array<int>,j:int,i:int,s:int)//maximum sum stuck to the right reads v requires 0<=j<=i<v.Length {(forall l,ss {:induction l}::j<=l<=i && ss==i+1 ==> Sum2(v,l,ss)<=s)} method segSumaMaxima2(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum2(v,k,i+1) && SumMaxToRight2(v,0,i,s) //Implement and verify { s:=v[i]; k:=i; var j:=i; var maxs:=s; while(j>0) { s:=s+v[j-1]; if(s>maxs){ maxs:=s; k:=j-1; } j:=j-1; } s:=maxs; }
function Sum(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length decreases j { if (i==j) then 0 else Sum(v,i,j-1)+v[j-1] } predicate SumMaxToRight(v:array<int>,i:int,s:int) reads v requires 0<=i<v.Length { forall l,ss {:induction l}::0<=l<=i && ss==i+1==> Sum(v,l,ss)<=s } method segMaxSum(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum(v,k,i+1) && SumMaxToRight(v,i,s) { s:=v[0]; k:=0; var j:=0; while (j<i) decreases i-j invariant 0<=j<=i invariant 0<=k<=j && s==Sum(v,k,j+1) invariant SumMaxToRight(v,j,s) { if (s+v[j+1]>v[j+1]) {s:=s+v[j+1];} else {k:=j+1;s:=v[j+1];} j:=j+1; } } function Sum2(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length decreases j-i { if (i==j) then 0 else v[i]+Sum2(v,i+1,j) } //Now do the same but with a loop from right to left predicate SumMaxToRight2(v:array<int>,j:int,i:int,s:int)//maximum sum stuck to the right reads v requires 0<=j<=i<v.Length {(forall l,ss {:induction l}::j<=l<=i && ss==i+1 ==> Sum2(v,l,ss)<=s)} method segSumaMaxima2(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum2(v,k,i+1) && SumMaxToRight2(v,0,i,s) //Implement and verify { s:=v[i]; k:=i; var j:=i; var maxs:=s; while(j>0) decreases j invariant 0<=j<=i invariant 0<=k<=i invariant s==Sum2(v,j,i+1) invariant SumMaxToRight2(v,j,i,maxs) invariant maxs==Sum2(v,k,i+1) { s:=s+v[j-1]; if(s>maxs){ maxs:=s; k:=j-1; } j:=j-1; } s:=maxs; }
Dafny-Exercises_tmp_tmpjm75muf__Session9Exercises_ExerciseSeqMaxSum.dfy
106
106
Dafny program: 106
/* https://leetcode.com/problems/two-sum/ function twoSum(nums: number[], target: number): number[] { const n = nums.length; for(let i = 0; i < n; i++) { for(let k = i+1; k < n; k++) { if(nums[i] + nums[k] == target) return [i,k]; } } }; */ predicate summingPair(i: nat, j: nat, nums: seq<int>, target: int) requires i < |nums| requires j < |nums| { i != j && nums[i] + nums[j] == target } method twoSum(nums: seq<int>, target: int) returns (pair: (nat, nat)) requires exists i:nat,j:nat :: i < j < |nums| && summingPair(i, j, nums, target) && forall l: nat, m: nat :: l < m < |nums| && l != i && m != j ==> !summingPair(l, m, nums, target) ensures 0 <= pair.0 < |nums| && 0 <= pair.1 < |nums| && summingPair(pair.0, pair.1, nums, target) { pair := (0,0); var i: nat := 0; while i < |nums| { var k: nat := i + 1; while k < |nums| // invariant forall q: nat :: i+1 <= q < k < |nums| ==> !summingPair(i,q, nums, target) //this fails to verify { // assert i < k < |nums|; if nums[i] + nums[k] == target { pair := (i,k); return pair; } k := k + 1; } i := i + 1; } }
/* https://leetcode.com/problems/two-sum/ function twoSum(nums: number[], target: number): number[] { const n = nums.length; for(let i = 0; i < n; i++) { for(let k = i+1; k < n; k++) { if(nums[i] + nums[k] == target) return [i,k]; } } }; */ predicate summingPair(i: nat, j: nat, nums: seq<int>, target: int) requires i < |nums| requires j < |nums| { i != j && nums[i] + nums[j] == target } method twoSum(nums: seq<int>, target: int) returns (pair: (nat, nat)) requires exists i:nat,j:nat :: i < j < |nums| && summingPair(i, j, nums, target) && forall l: nat, m: nat :: l < m < |nums| && l != i && m != j ==> !summingPair(l, m, nums, target) ensures 0 <= pair.0 < |nums| && 0 <= pair.1 < |nums| && summingPair(pair.0, pair.1, nums, target) { pair := (0,0); var i: nat := 0; while i < |nums| invariant i <= |nums| invariant forall z: nat, j: nat :: 0 <= z < i && z+1 <= j < |nums| ==> !summingPair(z, j, nums, target) { var k: nat := i + 1; while k < |nums| invariant i + 1 <= k <= |nums| // invariant forall q: nat :: i+1 <= q < k < |nums| ==> !summingPair(i,q, nums, target) //this fails to verify invariant forall q: nat :: i+1 <= q < k <= |nums| ==> !summingPair(i,q, nums, target) //this verifies { // assert i < k < |nums|; if nums[i] + nums[k] == target { pair := (i,k); return pair; } k := k + 1; } i := i + 1; } }
Dafny-Grind75_tmp_tmpsxfz3i4r_problems_twoSum.dfy
107
107
Dafny program: 107
datatype Tree = Empty | Node(int,Tree,Tree) method Main() { var tree := BuildBST([-2,8,3,9,2,-7,0]); PrintTreeNumbersInorder(tree); } method PrintTreeNumbersInorder(t: Tree) { match t { case Empty => case Node(n, l, r) => PrintTreeNumbersInorder(l); print n; print "\n"; PrintTreeNumbersInorder(r); } } function NumbersInTree(t: Tree): set<int> { NumbersInSequence(Inorder(t)) } function NumbersInSequence(q: seq<int>): set<int> { set x | x in q } predicate BST(t: Tree) { Ascending(Inorder(t)) } function Inorder(t: Tree): seq<int> { match t { case Empty => [] case Node(n',nt1,nt2) => Inorder(nt1)+[n']+Inorder(nt2) } } predicate Ascending(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] < q[j] } predicate NoDuplicates(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] != q[j] } /* Goal: Implement correctly, clearly. No need to document the proof obligations. */ method BuildBST(q: seq<int>) returns (t: Tree) requires NoDuplicates(q) ensures BST(t) && NumbersInTree(t) == NumbersInSequence(q) { t := Empty; for i:=0 to |q| { t := InsertBST(t,q[i]); } } /* Goal: Implement correctly, efficiently, clearly, documenting the proof obligations as we've learned, with assertions and a lemma for each proof goal */ method InsertBST(t0: Tree, x: int) returns (t: Tree) requires BST(t0) && x !in NumbersInTree(t0) ensures BST(t) && NumbersInTree(t) == NumbersInTree(t0)+{x} { match t0 { case Empty => t := Node(x, Empty, Empty); case Node(i, left, right) => { var tmp:Tree:= Empty; if x < i { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(left, x); t := Node(i, tmp, right); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); // assert all_nums[..|left_nums|] == left_nums; ghost var new_all_nums := Inorder(t); ghost var new_left_nums := Inorder(tmp); // assert Ascending(new_left_nums+ [i] + right_nums); lemma_all_small(new_left_nums,i); } else { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(right, x); t := Node(i, left, tmp); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); // assert all_nums[..|left_nums|] == left_nums; ghost var new_all_nums := Inorder(t); ghost var new_right_nums := Inorder(tmp); // assert Ascending(left_nums+ [i] + right_nums); // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..]) ==> j > i; // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..])+{x} ==> j > i; lemma_all_big(new_right_nums,i); // assert Ascending(new_right_nums+[i]); } } } } lemma LemmaBinarySearchSubtree(n: int, left: Tree, right: Tree) requires BST(Node(n, left, right)) ensures BST(left) && BST(right) { var qleft, qright := Inorder(left), Inorder(right); var q := qleft+[n]+qright; } lemma LemmaAscendingSubsequence(q1: seq<int>, q2: seq<int>, i: nat) requires i <= |q1|-|q2| && q2 == q1[i..i+|q2|] requires Ascending(q1) ensures Ascending(q2) {} lemma {:verify true} lemma_all_small(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k < i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] < i {} lemma {:verify true} lemma_all_big(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k > i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] > i {}
datatype Tree = Empty | Node(int,Tree,Tree) method Main() { var tree := BuildBST([-2,8,3,9,2,-7,0]); PrintTreeNumbersInorder(tree); } method PrintTreeNumbersInorder(t: Tree) { match t { case Empty => case Node(n, l, r) => PrintTreeNumbersInorder(l); print n; print "\n"; PrintTreeNumbersInorder(r); } } function NumbersInTree(t: Tree): set<int> { NumbersInSequence(Inorder(t)) } function NumbersInSequence(q: seq<int>): set<int> { set x | x in q } predicate BST(t: Tree) { Ascending(Inorder(t)) } function Inorder(t: Tree): seq<int> { match t { case Empty => [] case Node(n',nt1,nt2) => Inorder(nt1)+[n']+Inorder(nt2) } } predicate Ascending(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] < q[j] } predicate NoDuplicates(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] != q[j] } /* Goal: Implement correctly, clearly. No need to document the proof obligations. */ method BuildBST(q: seq<int>) returns (t: Tree) requires NoDuplicates(q) ensures BST(t) && NumbersInTree(t) == NumbersInSequence(q) { t := Empty; for i:=0 to |q| invariant BST(t); invariant NumbersInTree(t) == NumbersInSequence(q[..i]) { t := InsertBST(t,q[i]); } } /* Goal: Implement correctly, efficiently, clearly, documenting the proof obligations as we've learned, with assertions and a lemma for each proof goal */ method InsertBST(t0: Tree, x: int) returns (t: Tree) requires BST(t0) && x !in NumbersInTree(t0) ensures BST(t) && NumbersInTree(t) == NumbersInTree(t0)+{x} { match t0 { case Empty => t := Node(x, Empty, Empty); case Node(i, left, right) => { var tmp:Tree:= Empty; if x < i { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(left, x); t := Node(i, tmp, right); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); assert all_nums == left_nums + [i] + right_nums; assert all_nums[|left_nums|] == i; assert all_nums[|left_nums|+1..] == right_nums; // assert all_nums[..|left_nums|] == left_nums; assert Ascending(right_nums); assert Ascending(left_nums); assert Ascending(left_nums + [i] + right_nums); assert forall j,k :: |left_nums| < j < k < |all_nums| ==> x < i < all_nums[j] < all_nums[k]; ghost var new_all_nums := Inorder(t); ghost var new_left_nums := Inorder(tmp); assert new_all_nums == (new_left_nums + [i] + right_nums); assert Ascending([i]+right_nums); assert Ascending(new_left_nums); assert NumbersInSequence(new_left_nums) == NumbersInSequence(left_nums) + {x}; // assert Ascending(new_left_nums+ [i] + right_nums); assert forall j,k::0<= j < k <|all_nums| ==> all_nums[j]<all_nums[k]; assert forall j,k::0<= j < k <|left_nums| ==> all_nums[j]<all_nums[k]<all_nums[|left_nums|]; assert all_nums[|left_nums|] == i; assert left_nums == all_nums[..|left_nums|]; assert NumbersInSequence(new_left_nums) == NumbersInSequence(all_nums[..|left_nums|])+{x}; assert forall j,k::0<=j < k < |left_nums| ==> left_nums[j] < left_nums[k] < i; assert x < i; assert forall j :: j in NumbersInSequence(all_nums[..|left_nums|]) ==> j < i; assert forall j :: j in NumbersInSequence(all_nums[..|left_nums|])+{x} ==> j < i; assert forall j :: j in NumbersInSequence(new_left_nums) ==> j < i; assert forall j :: j in NumbersInSequence(new_left_nums) <==> j in new_left_nums; assert forall j,k::0<=j < k < |new_left_nums| ==> new_left_nums[j] < new_left_nums[k]; assert x < i; lemma_all_small(new_left_nums,i); assert forall j::0<=j < |new_left_nums| ==> new_left_nums[j] < i; assert Ascending(new_left_nums+[i]); assert Ascending(Inorder(t)); assert BST(t); } else { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(right, x); t := Node(i, left, tmp); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); assert all_nums == left_nums + [i] + right_nums; assert all_nums[|left_nums|] == i; assert all_nums[|left_nums|+1..] == right_nums; // assert all_nums[..|left_nums|] == left_nums; assert Ascending(right_nums); assert Ascending(left_nums); assert Ascending(left_nums + [i] + right_nums); assert forall j,k :: 0 <= j < k < |left_nums| ==> all_nums[j] < all_nums[k] < i < x; ghost var new_all_nums := Inorder(t); ghost var new_right_nums := Inorder(tmp); assert new_all_nums == (left_nums + [i] + new_right_nums); assert Ascending(left_nums + [i]); assert Ascending(new_right_nums); assert NumbersInSequence(new_right_nums) == NumbersInSequence(right_nums) + {x}; // assert Ascending(left_nums+ [i] + right_nums); assert forall j,k::0<= j < k <|all_nums| ==> all_nums[j]<all_nums[k]; assert forall j,k::|left_nums| < j < k < |all_nums|==> all_nums[|left_nums|]<all_nums[j]<all_nums[k]; assert all_nums[|left_nums|] == i; assert left_nums == all_nums[..|left_nums|]; assert NumbersInSequence(new_right_nums) == NumbersInSequence(all_nums[|left_nums|+1..])+{x}; assert forall j,k::0<=j < k < |right_nums| ==> i < right_nums[j] < right_nums[k] ; assert x > i; // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..]) ==> j > i; // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..])+{x} ==> j > i; assert forall j :: j in NumbersInSequence(new_right_nums) ==> j > i; assert forall j :: j in NumbersInSequence(new_right_nums) <==> j in new_right_nums; assert forall j,k::0<=j < k < |new_right_nums| ==> new_right_nums[j] < new_right_nums[k]; assert x > i; lemma_all_big(new_right_nums,i); assert forall j::0<=j < |new_right_nums| ==> new_right_nums[j] > i; // assert Ascending(new_right_nums+[i]); assert Ascending(Inorder(t)); assert BST(t); } } } } lemma LemmaBinarySearchSubtree(n: int, left: Tree, right: Tree) requires BST(Node(n, left, right)) ensures BST(left) && BST(right) { assert Ascending(Inorder(Node(n, left, right))); var qleft, qright := Inorder(left), Inorder(right); var q := qleft+[n]+qright; assert q == Inorder(Node(n, left, right)); assert Ascending(qleft+[n]+qright); assert Ascending(qleft) by { LemmaAscendingSubsequence(q, qleft, 0); } assert Ascending(qright) by { LemmaAscendingSubsequence(q, qright, |qleft|+1); } } lemma LemmaAscendingSubsequence(q1: seq<int>, q2: seq<int>, i: nat) requires i <= |q1|-|q2| && q2 == q1[i..i+|q2|] requires Ascending(q1) ensures Ascending(q2) {} lemma {:verify true} lemma_all_small(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k < i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] < i {} lemma {:verify true} lemma_all_big(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k > i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] > i {}
Dafny-Practice_tmp_tmphnmt4ovh_BST.dfy
108
108
Dafny program: 108
method {:verify true} FindAllOccurrences(text: string, pattern: string) returns (offsets: set<nat>) ensures forall i :: i in offsets ==> i + |pattern| <= |text| ensures forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets) { offsets := {}; var i:int := 0; // no pattern in text at all. if |pattern| > |text| { return offsets; } //all offsets are offsets of pattern/ if pattern == "" { while i < |text| { offsets := offsets + {i}; i:=i+1; } offsets := offsets + {|text|}; return offsets; } var pattern_hash: int := RecursiveSumDown(pattern); var text_hash: int := RecursiveSumDown(text[..|pattern|]); if pattern_hash == text_hash{ if text[..|pattern|] == pattern { offsets := offsets + {0}; } } else { LemmaRabinKarp(text[..|pattern|], pattern, text_hash, pattern_hash); } while i < |text| - |pattern| { //updating text hash var old_text_hash := text_hash; var left_letter_as_int := text[i] as int; var right_new_letter_as_int := text[i+|pattern|] as int; text_hash := text_hash - left_letter_as_int + right_new_letter_as_int; //updating i i := i + 1; //checking hash equality if pattern_hash == text_hash{ if text[i..i + |pattern|] == pattern { offsets := offsets + {i}; } LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); } else{ LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); LemmaRabinKarp(text[i..i+|pattern|], pattern, text_hash, pattern_hash); } Lemma2Sides(text, pattern, i, offsets); //=> //=> } //=> } function RecursiveSumDown(str: string): int { if str == "" then 0 else str[|str|-1] as int +RecursiveSumDown(str[..|str|-1]) } function RecursiveSumUp(str: string): int { if str == "" then 0 else str[0] as int + RecursiveSumUp(str[1..]) } lemma {:verify true}LemmaRabinKarp(t_sub:string, pattern:string, text_hash:int, pattern_hash:int) requires text_hash != pattern_hash requires pattern_hash == RecursiveSumDown(pattern) requires text_hash == RecursiveSumDown(t_sub) ensures t_sub[..] != pattern[..] {} lemma Lemma2Sides(text: string, pattern: string, i: nat, offsets: set<nat>) requires 0 <= i <= |text| - |pattern| requires (text[i..i+|pattern|] == pattern ==> i in offsets) requires (text[i..i+|pattern|] == pattern <== i in offsets) ensures (text[i..i+|pattern|] == pattern <==> i in offsets) {} lemma LemmaHashEqualty(text_hash : int, text: string, i: nat, old_text_hash: int, pattern: string) requires 0 < i <= |text| - |pattern| requires text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int requires old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); ensures text_hash == RecursiveSumDown(text[i..i+|pattern|]) { ghost var temp_val := old_text_hash + text[i - 1 + |pattern|] as int; //=> ghost var str := text[i - 1..]; LemmaAddingOneIndex(str, |pattern|, old_text_hash); //=> //=> PrependSumUp(text[i - 1..i + |pattern|]); EquivalentSumDefinitions(text[i - 1..i + |pattern|]); EquivalentSumDefinitions(text[i..i + |pattern|]); //=> //=> //=> //=> } lemma LemmaAddingOneIndex(str: string, i: nat, sum: int) requires 0 <= i < |str| && sum == RecursiveSumDown(str[..i]) ensures 0 <= i+1 <= |str| && sum + str[i] as int == RecursiveSumDown(str[..i+1]) { var str1 := str[..i+1]; calc { RecursiveSumDown(str[..i+1]); == // def. if str1 == [] then 0 else str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert str1 != []; } // simplification for a non-empty sequence str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert |str1|-1 == i; } str1[i] as int + RecursiveSumDown(str1[..i]); == { assert str1[..i] == str[..i]; } str[i] as int + RecursiveSumDown(str[..i]); == // inv. str[i] as int + sum; == sum + str[i] as int; } } lemma PrependSumUp(str: string) requires str != "" ensures RecursiveSumUp(str) == str[0] as int + RecursiveSumUp(str[1..]) { // directly from the definition of RecursiveSumUp (for a non-emty sequence) } lemma EquivalentSumDefinitions(str: string) ensures RecursiveSumDown(str) == RecursiveSumUp(str) { if |str| == 0 { } else if |str| == 1 { } else { var first: char, mid: string, last:char := str[0], str[1..|str|-1], str[|str|-1]; calc { RecursiveSumDown(str); == { assert str != [] && str[|str|-1] == last && str[..|str|-1] == [first] + mid; } last as int + RecursiveSumDown([first] + mid); == // arithmetic RecursiveSumDown([first] + mid) + last as int; == { EquivalentSumDefinitions([first] + mid); } // induction hypothesis RecursiveSumUp([first] + mid) + last as int; == { assert [first] + mid != []; } first as int + RecursiveSumUp(mid) + last as int; == { EquivalentSumDefinitions(mid); } // induction hypothesis first as int + RecursiveSumDown(mid) + last as int; == first as int + RecursiveSumDown(mid + [last]); == { EquivalentSumDefinitions(mid + [last]); } // induction hypothesis first as int + RecursiveSumUp(mid + [last]); == { assert str != [] && str[0] == first && str[1..] == mid + [last]; } RecursiveSumUp(str); } } }
method {:verify true} FindAllOccurrences(text: string, pattern: string) returns (offsets: set<nat>) ensures forall i :: i in offsets ==> i + |pattern| <= |text| ensures forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets) { offsets := {}; var i:int := 0; // no pattern in text at all. if |pattern| > |text| { assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); return offsets; } //all offsets are offsets of pattern/ if pattern == "" { while i < |text| invariant 0 <= i <=|text| invariant forall j :: 0 <= j < i ==> (text[j..j+|pattern|] == pattern <==> j in offsets) invariant forall j :: j in offsets ==> j + |pattern| <= |text| { offsets := offsets + {i}; i:=i+1; } offsets := offsets + {|text|}; assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); return offsets; } var pattern_hash: int := RecursiveSumDown(pattern); var text_hash: int := RecursiveSumDown(text[..|pattern|]); assert text_hash == RecursiveSumDown(text[..|pattern|]); if pattern_hash == text_hash{ if text[..|pattern|] == pattern { offsets := offsets + {0}; } } else { LemmaRabinKarp(text[..|pattern|], pattern, text_hash, pattern_hash); } while i < |text| - |pattern| invariant 0 <= i <= |text| - |pattern| invariant text_hash == RecursiveSumDown(text[i..i + |pattern|]) invariant forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets) invariant forall i :: i in offsets ==> i + |pattern| <= |text| invariant forall k :: i < k ==> (k in offsets) == false decreases |text| - |pattern| - i { assert text_hash == RecursiveSumDown(text[i..i + |pattern|]); assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); //updating text hash var old_text_hash := text_hash; assert old_text_hash == RecursiveSumDown(text[i..i + |pattern|]); var left_letter_as_int := text[i] as int; var right_new_letter_as_int := text[i+|pattern|] as int; text_hash := text_hash - left_letter_as_int + right_new_letter_as_int; //updating i assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert text_hash == old_text_hash - text[i] as int + text[i+|pattern|] as int; assert old_text_hash == RecursiveSumDown(text[i..i + |pattern|]); i := i + 1; assert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); assert forall k :: 0 <= k < i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int; //checking hash equality if pattern_hash == text_hash{ if text[i..i + |pattern|] == pattern { assert (text[i..i + |pattern|] == pattern); offsets := offsets + {i}; assert (i in offsets); assert text[i..i+|pattern|] == pattern <== i in offsets; assert text[i..i+|pattern|] == pattern ==> i in offsets; } assert pattern_hash == RecursiveSumDown(pattern); assert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int; assert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); assert text_hash == RecursiveSumDown(text[i..i+|pattern|]); } else{ assert text_hash != pattern_hash; assert pattern_hash == RecursiveSumDown(pattern); assert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int; assert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); assert text_hash == RecursiveSumDown(text[i..i+|pattern|]); LemmaRabinKarp(text[i..i+|pattern|], pattern, text_hash, pattern_hash); assert text[i..i+|pattern|] == pattern ==> i in offsets; assert (i in offsets) == false; assert text[i..i+|pattern|] == pattern <== i in offsets; } assert text[i..i+|pattern|] == pattern ==> i in offsets; assert text[i..i+|pattern|] == pattern <== i in offsets; Lemma2Sides(text, pattern, i, offsets); //=> assert text[i..i+|pattern|] == pattern <==> i in offsets; assert forall k :: 0 <= k < i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); //=> assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert text_hash == RecursiveSumDown(text[i..i+|pattern|]); } assert 0 <= i <= |text| - |pattern|; assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall k :: i < k ==> (k in offsets) == false; assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert i >= |text| - |pattern|; //=> assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); } function RecursiveSumDown(str: string): int decreases |str| { if str == "" then 0 else str[|str|-1] as int +RecursiveSumDown(str[..|str|-1]) } function RecursiveSumUp(str: string): int decreases |str| { if str == "" then 0 else str[0] as int + RecursiveSumUp(str[1..]) } lemma {:verify true}LemmaRabinKarp(t_sub:string, pattern:string, text_hash:int, pattern_hash:int) requires text_hash != pattern_hash requires pattern_hash == RecursiveSumDown(pattern) requires text_hash == RecursiveSumDown(t_sub) ensures t_sub[..] != pattern[..] {} lemma Lemma2Sides(text: string, pattern: string, i: nat, offsets: set<nat>) requires 0 <= i <= |text| - |pattern| requires (text[i..i+|pattern|] == pattern ==> i in offsets) requires (text[i..i+|pattern|] == pattern <== i in offsets) ensures (text[i..i+|pattern|] == pattern <==> i in offsets) {} lemma LemmaHashEqualty(text_hash : int, text: string, i: nat, old_text_hash: int, pattern: string) requires 0 < i <= |text| - |pattern| requires text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int requires old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); ensures text_hash == RecursiveSumDown(text[i..i+|pattern|]) { assert 0 < i <= |text| - |pattern|; assert 0 <= i - 1 < |text| - |pattern|; ghost var temp_val := old_text_hash + text[i - 1 + |pattern|] as int; assert text_hash == old_text_hash + text[i - 1 + |pattern|] as int - text[i - 1] as int; //=> assert text_hash == temp_val - text[i - 1] as int; assert 0 <= |pattern| < |text[i - 1..]|; ghost var str := text[i - 1..]; assert str[..|pattern|] == text[i - 1 .. i - 1 + |pattern|]; assert old_text_hash == RecursiveSumDown(str[..|pattern|]); LemmaAddingOneIndex(str, |pattern|, old_text_hash); assert old_text_hash + str[|pattern|] as int == RecursiveSumDown(str[..|pattern|+1]); assert str[..|pattern|+1] == text[i - 1..i - 1 + |pattern| + 1]; //=> assert old_text_hash + text[i - 1 + |pattern|] as int == RecursiveSumDown(text[i - 1..i - 1 + |pattern| + 1]); assert temp_val == old_text_hash + text[i - 1 + |pattern|] as int; //=> assert temp_val == RecursiveSumDown(text[i - 1..i - 1 + |pattern| + 1]); assert temp_val == RecursiveSumDown(text[i - 1..i + |pattern|]); PrependSumUp(text[i - 1..i + |pattern|]); assert RecursiveSumUp(text[i - 1..i + |pattern|]) == text[i - 1] as int + RecursiveSumUp(text[i..i + |pattern|]); EquivalentSumDefinitions(text[i - 1..i + |pattern|]); EquivalentSumDefinitions(text[i..i + |pattern|]); //=> assert RecursiveSumUp(text[i - 1..i + |pattern|]) == RecursiveSumDown(text[i - 1..i + |pattern|]); assert RecursiveSumUp(text[i..i + |pattern|]) == RecursiveSumDown(text[i..i + |pattern|]); //=> assert RecursiveSumDown(text[i - 1..i + |pattern|]) == text[i - 1] as int + RecursiveSumDown(text[i..i + |pattern|]); //=> assert RecursiveSumDown(text[i - 1..i + |pattern|]) - text[i - 1] as int == RecursiveSumDown(text[i..i + |pattern|]); assert text_hash == temp_val - text[i - 1] as int; assert temp_val == RecursiveSumDown(text[i - 1..i + |pattern|]); assert text_hash == RecursiveSumDown(text[i - 1..i + |pattern|]) - text[i - 1] as int; //=> assert text_hash == RecursiveSumDown(text[i..i + |pattern|]); } lemma LemmaAddingOneIndex(str: string, i: nat, sum: int) requires 0 <= i < |str| && sum == RecursiveSumDown(str[..i]) ensures 0 <= i+1 <= |str| && sum + str[i] as int == RecursiveSumDown(str[..i+1]) { var str1 := str[..i+1]; calc { RecursiveSumDown(str[..i+1]); == // def. if str1 == [] then 0 else str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert str1 != []; } // simplification for a non-empty sequence str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert |str1|-1 == i; } str1[i] as int + RecursiveSumDown(str1[..i]); == { assert str1[..i] == str[..i]; } str[i] as int + RecursiveSumDown(str[..i]); == // inv. str[i] as int + sum; == sum + str[i] as int; } } lemma PrependSumUp(str: string) requires str != "" ensures RecursiveSumUp(str) == str[0] as int + RecursiveSumUp(str[1..]) { // directly from the definition of RecursiveSumUp (for a non-emty sequence) } lemma EquivalentSumDefinitions(str: string) ensures RecursiveSumDown(str) == RecursiveSumUp(str) decreases |str| { if |str| == 0 { assert str == ""; assert RecursiveSumDown([]) == 0 == RecursiveSumUp([]); } else if |str| == 1 { assert str == [str[0]]; assert RecursiveSumDown(str) == str[0] as int == RecursiveSumUp(str); } else { assert |str| >= 2; var first: char, mid: string, last:char := str[0], str[1..|str|-1], str[|str|-1]; assert str == [first] + mid + [last]; calc { RecursiveSumDown(str); == { assert str != [] && str[|str|-1] == last && str[..|str|-1] == [first] + mid; } last as int + RecursiveSumDown([first] + mid); == // arithmetic RecursiveSumDown([first] + mid) + last as int; == { EquivalentSumDefinitions([first] + mid); } // induction hypothesis RecursiveSumUp([first] + mid) + last as int; == { assert [first] + mid != []; } first as int + RecursiveSumUp(mid) + last as int; == { EquivalentSumDefinitions(mid); } // induction hypothesis first as int + RecursiveSumDown(mid) + last as int; == first as int + RecursiveSumDown(mid + [last]); == { EquivalentSumDefinitions(mid + [last]); } // induction hypothesis first as int + RecursiveSumUp(mid + [last]); == { assert str != [] && str[0] == first && str[1..] == mid + [last]; } RecursiveSumUp(str); } } }
Dafny-Practice_tmp_tmphnmt4ovh_Pattern Matching.dfy
109
109
Dafny program: 109
method ArraySplit (a : array<int>) returns (b : array<int>, c : array<int>) ensures fresh(b) ensures fresh(c) ensures a[..] == b[..] + c[..] ensures a.Length == b.Length + c.Length ensures a.Length > 1 ==> a.Length > b.Length ensures a.Length > 1 ==> a.Length > c.Length { var splitPoint : int := a.Length / 2; b := new int[splitPoint]; c := new int[a.Length - splitPoint]; var i : int := 0; while (i < splitPoint) { b[i] := a[i]; i := i + 1; } // while(i < a.Length) // invariant splitPoint <= i <= a.Length // invariant c[..i-splitPoint] == a[..i] // { // c[i] := a[i]; // i := i+1; // } var j : int := 0; while (i < a.Length) { c[j] := a[i]; i := i + 1; j := j + 1; } }
method ArraySplit (a : array<int>) returns (b : array<int>, c : array<int>) ensures fresh(b) ensures fresh(c) ensures a[..] == b[..] + c[..] ensures a.Length == b.Length + c.Length ensures a.Length > 1 ==> a.Length > b.Length ensures a.Length > 1 ==> a.Length > c.Length { var splitPoint : int := a.Length / 2; b := new int[splitPoint]; c := new int[a.Length - splitPoint]; var i : int := 0; while (i < splitPoint) invariant 0 <= i <= splitPoint invariant b[..i] == a[..i] { b[i] := a[i]; i := i + 1; } // while(i < a.Length) // invariant splitPoint <= i <= a.Length // invariant c[..i-splitPoint] == a[..i] // { // c[i] := a[i]; // i := i+1; // } var j : int := 0; while (i < a.Length) invariant splitPoint <= i <= a.Length invariant j == i - splitPoint invariant c[..j] == a[splitPoint..i] invariant b[..] + c[..j] == a[..i] { c[j] := a[i]; i := i + 1; j := j + 1; } }
Dafny-Projects_tmp_tmph399drhy_p2_arraySplit.dfy
110
110
Dafny program: 110
module Exponential { ghost function {:axiom} Exp(x: real): real lemma {:axiom} FunctionalEquation(x: real, y: real) ensures Exp(x + y) == Exp(x) * Exp(y) lemma {:axiom} Increasing(x: real, y: real) requires x < y ensures Exp(x) < Exp(y) lemma {:axiom} EvalOne() ensures 2.718281828 <= Exp(1.0) <= 2.718281829 lemma Positive(x: real) ensures Exp(x) > 0.0 { var sqrt := Exp(x / 2.0); calc { Exp(x); { FunctionalEquation(x / 2.0, x / 2.0); } sqrt * sqrt; >= 0.0; } } if Exp(x) == 0.0 { calc { 0.0; Exp(x); < { Increasing(x, x + 1.0); } Exp(x + 1.0); { FunctionalEquation(x, 1.0); } Exp(x) * Exp(1.0); == 0.0; } } } lemma EvalZero() ensures Exp(0.0) == 1.0 { var one := Exp(0.0); Positive(0.0); } FunctionalEquation(0.0, 0.0); } } }
module Exponential { ghost function {:axiom} Exp(x: real): real lemma {:axiom} FunctionalEquation(x: real, y: real) ensures Exp(x + y) == Exp(x) * Exp(y) lemma {:axiom} Increasing(x: real, y: real) requires x < y ensures Exp(x) < Exp(y) lemma {:axiom} EvalOne() ensures 2.718281828 <= Exp(1.0) <= 2.718281829 lemma Positive(x: real) ensures Exp(x) > 0.0 { assert Exp(x) >= 0.0 by { var sqrt := Exp(x / 2.0); calc { Exp(x); { FunctionalEquation(x / 2.0, x / 2.0); } sqrt * sqrt; >= 0.0; } } if Exp(x) == 0.0 { calc { 0.0; Exp(x); < { Increasing(x, x + 1.0); } Exp(x + 1.0); { FunctionalEquation(x, 1.0); } Exp(x) * Exp(1.0); == 0.0; } } } lemma EvalZero() ensures Exp(0.0) == 1.0 { var one := Exp(0.0); assert one > 0.0 by { Positive(0.0); } assert one * one == one by { FunctionalEquation(0.0, 0.0); } } }
Dafny-VMC_tmp_tmpzgqv0i1u_src_Math_Exponential.dfy
111
111
Dafny program: 111
/******************************************************************************* * Copyright by the contributors to the Dafny Project * SPDX-License-Identifier: MIT *******************************************************************************/ module Helper { /************ Definitions ************/ function Power(b: nat, n: nat): (p: nat) ensures b > 0 ==> p > 0 { match n case 0 => 1 case 1 => b case _ => b * Power(b, n - 1) } function Log2Floor(n: nat): nat requires n >= 1 { if n < 2 then 0 else Log2Floor(n / 2) + 1 } lemma Log2FloorDef(n: nat) requires n >= 1 ensures Log2Floor(2 * n) == Log2Floor(n) + 1 {} function boolToNat(b: bool): nat { if b then 1 else 0 } /******* Lemmas *******/ lemma Congruence<T, U>(x: T, y: T, f: T -> U) requires x == y ensures f(x) == f(y) {} lemma DivisionSubstituteAlternativeReal(x: real, a: real, b: real) requires a == b requires x != 0.0 ensures a / x == b / x {} lemma DivModAddDenominator(n: nat, m: nat) requires m > 0 ensures (n + m) / m == n / m + 1 ensures (n + m) % m == n % m { var zp := (n + m) / m - n / m - 1; } lemma DivModIsUnique(n: int, m: int, a: int, b: int) requires n >= 0 requires m > 0 requires 0 <= b < m requires n == a * m + b ensures a == n / m ensures b == n % m { if a == 0 { } else { } } lemma DivModAddMultiple(a: nat, b: nat, c: nat) requires a > 0 ensures (c * a + b) / a == c + b / a ensures (c * a + b) % a == b % a { calc { a * c + b; == a * c + (a * (b / a) + b % a); == a * (c + b / a) + b % a; } DivModIsUnique(a * c + b, a, c + b / a, b % a); } lemma DivisionByTwo(x: real) ensures 0.5 * x == x / 2.0 {} lemma PowerGreater0(base: nat, exponent: nat) requires base >= 1 ensures Power(base, exponent) >= 1 {} lemma Power2OfLog2Floor(n: nat) requires n >= 1 ensures Power(2, Log2Floor(n)) <= n < Power(2, Log2Floor(n) + 1) {} lemma NLtPower2Log2FloorOf2N(n: nat) requires n >= 1 ensures n < Power(2, Log2Floor(2 * n)) { calc { n; < { Power2OfLog2Floor(n); } Power(2, Log2Floor(n) + 1); == { Log2FloorDef(n); } Power(2, Log2Floor(2 * n)); } } lemma MulMonotonic(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d ensures a * b <= c * d { calc { a * b; <= c * b; <= c * d; } } lemma MulMonotonicStrictRhs(b: nat, c: nat, d: nat) requires b < d requires c > 0 ensures c * b < c * d {} lemma MulMonotonicStrict(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d requires (a != c && d > 0) || (b != d && c > 0) ensures a * b < c * d { if a != c && d > 0 { calc { a * b; <= { MulMonotonic(a, b, a, d); } a * d; < c * d; } } if b != d && c > 0 { calc { a * b; <= c * b; < { MulMonotonicStrictRhs(b, c, d); } c * d; } } } lemma AdditionOfFractions(x: real, y: real, z: real) requires z != 0.0 ensures (x / z) + (y / z) == (x + y) / z {} lemma DivSubstituteDividend(x: real, y: real, z: real) requires y != 0.0 requires x == z ensures x / y == z / y {} lemma DivSubstituteDivisor(x: real, y: real, z: real) requires y != 0.0 requires y == z ensures x / y == x / z {} lemma DivDivToDivMul(x: real, y: real, z: real) requires y != 0.0 requires z != 0.0 ensures (x / y) / z == x / (y * z) {} lemma NatMulNatToReal(x: nat, y: nat) ensures (x * y) as real == (x as real) * (y as real) {} lemma SimplifyFractions(x: real, y: real, z: real) requires z != 0.0 requires y != 0.0 ensures (x / z) / (y / z) == x / y {} lemma PowerOfTwoLemma(k: nat) ensures (1.0 / Power(2, k) as real) / 2.0 == 1.0 / (Power(2, k + 1) as real) { calc { (1.0 / Power(2, k) as real) / 2.0; == { DivDivToDivMul(1.0, Power(2, k) as real, 2.0); } 1.0 / (Power(2, k) as real * 2.0); == { NatMulNatToReal(Power(2, k), 2); } 1.0 / (Power(2, k) * 2) as real; == 1.0 / (Power(2, k + 1) as real); } } }
/******************************************************************************* * Copyright by the contributors to the Dafny Project * SPDX-License-Identifier: MIT *******************************************************************************/ module Helper { /************ Definitions ************/ function Power(b: nat, n: nat): (p: nat) ensures b > 0 ==> p > 0 { match n case 0 => 1 case 1 => b case _ => b * Power(b, n - 1) } function Log2Floor(n: nat): nat requires n >= 1 decreases n { if n < 2 then 0 else Log2Floor(n / 2) + 1 } lemma Log2FloorDef(n: nat) requires n >= 1 ensures Log2Floor(2 * n) == Log2Floor(n) + 1 {} function boolToNat(b: bool): nat { if b then 1 else 0 } /******* Lemmas *******/ lemma Congruence<T, U>(x: T, y: T, f: T -> U) requires x == y ensures f(x) == f(y) {} lemma DivisionSubstituteAlternativeReal(x: real, a: real, b: real) requires a == b requires x != 0.0 ensures a / x == b / x {} lemma DivModAddDenominator(n: nat, m: nat) requires m > 0 ensures (n + m) / m == n / m + 1 ensures (n + m) % m == n % m { var zp := (n + m) / m - n / m - 1; assert 0 == m * zp + ((n + m) % m) - (n % m); } lemma DivModIsUnique(n: int, m: int, a: int, b: int) requires n >= 0 requires m > 0 requires 0 <= b < m requires n == a * m + b ensures a == n / m ensures b == n % m { if a == 0 { assert n == b; } else { assert (n - m) / m == a - 1 && (n - m) % m == b by { DivModIsUnique(n - m, m, a - 1, b); } assert n / m == a && n % m == b by { DivModAddDenominator(n - m, m); } } } lemma DivModAddMultiple(a: nat, b: nat, c: nat) requires a > 0 ensures (c * a + b) / a == c + b / a ensures (c * a + b) % a == b % a { calc { a * c + b; == a * c + (a * (b / a) + b % a); == a * (c + b / a) + b % a; } DivModIsUnique(a * c + b, a, c + b / a, b % a); } lemma DivisionByTwo(x: real) ensures 0.5 * x == x / 2.0 {} lemma PowerGreater0(base: nat, exponent: nat) requires base >= 1 ensures Power(base, exponent) >= 1 {} lemma Power2OfLog2Floor(n: nat) requires n >= 1 ensures Power(2, Log2Floor(n)) <= n < Power(2, Log2Floor(n) + 1) {} lemma NLtPower2Log2FloorOf2N(n: nat) requires n >= 1 ensures n < Power(2, Log2Floor(2 * n)) { calc { n; < { Power2OfLog2Floor(n); } Power(2, Log2Floor(n) + 1); == { Log2FloorDef(n); } Power(2, Log2Floor(2 * n)); } } lemma MulMonotonic(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d ensures a * b <= c * d { calc { a * b; <= c * b; <= c * d; } } lemma MulMonotonicStrictRhs(b: nat, c: nat, d: nat) requires b < d requires c > 0 ensures c * b < c * d {} lemma MulMonotonicStrict(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d requires (a != c && d > 0) || (b != d && c > 0) ensures a * b < c * d { if a != c && d > 0 { calc { a * b; <= { MulMonotonic(a, b, a, d); } a * d; < c * d; } } if b != d && c > 0 { calc { a * b; <= c * b; < { MulMonotonicStrictRhs(b, c, d); } c * d; } } } lemma AdditionOfFractions(x: real, y: real, z: real) requires z != 0.0 ensures (x / z) + (y / z) == (x + y) / z {} lemma DivSubstituteDividend(x: real, y: real, z: real) requires y != 0.0 requires x == z ensures x / y == z / y {} lemma DivSubstituteDivisor(x: real, y: real, z: real) requires y != 0.0 requires y == z ensures x / y == x / z {} lemma DivDivToDivMul(x: real, y: real, z: real) requires y != 0.0 requires z != 0.0 ensures (x / y) / z == x / (y * z) {} lemma NatMulNatToReal(x: nat, y: nat) ensures (x * y) as real == (x as real) * (y as real) {} lemma SimplifyFractions(x: real, y: real, z: real) requires z != 0.0 requires y != 0.0 ensures (x / z) / (y / z) == x / y {} lemma PowerOfTwoLemma(k: nat) ensures (1.0 / Power(2, k) as real) / 2.0 == 1.0 / (Power(2, k + 1) as real) { calc { (1.0 / Power(2, k) as real) / 2.0; == { DivDivToDivMul(1.0, Power(2, k) as real, 2.0); } 1.0 / (Power(2, k) as real * 2.0); == { NatMulNatToReal(Power(2, k), 2); } 1.0 / (Power(2, k) * 2) as real; == 1.0 / (Power(2, k + 1) as real); } } }
Dafny-VMC_tmp_tmpzgqv0i1u_src_Math_Helper.dfy
112
112
Dafny program: 112
predicate sorted(a: array?<int>, l: int, u: int) reads a requires a != null { forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j] } method BinarySearch(a: array?<int>, key: int) returns (index: int) requires a != null && sorted(a,0,a.Length-1); ensures index >= 0 ==> index < a.Length && a[index] == key; ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key; { var low := 0; var high := a.Length; while (low < high) 0 <= i < a.Length && !(low <= i < high) ==> a[i] != key; { var mid := (low + high) / 2; if (a[mid] < key) { low := mid + 1; } else if (key < a[mid]) { high := mid; } else { return mid; } } return -1; }
predicate sorted(a: array?<int>, l: int, u: int) reads a requires a != null { forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j] } method BinarySearch(a: array?<int>, key: int) returns (index: int) requires a != null && sorted(a,0,a.Length-1); ensures index >= 0 ==> index < a.Length && a[index] == key; ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key; { var low := 0; var high := a.Length; while (low < high) invariant 0 <= low <= high <= a.Length; invariant forall i :: 0 <= i < a.Length && !(low <= i < high) ==> a[i] != key; { var mid := (low + high) / 2; if (a[mid] < key) { low := mid + 1; } else if (key < a[mid]) { high := mid; } else { return mid; } } return -1; }
Dafny-demo_tmp_tmpkgr_dvdi_Dafny_BinarySearch.dfy
113
113
Dafny program: 113
method FindMax(a: array<int>) returns (i: int) // Annotate this method with pre- and postconditions // that ensure it behaves as described. requires a.Length > 0 ensures 0<= i < a.Length ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i] { // Fill in the body that calculates the INDEX of the maximum. i := 0; var index := 1; while index < a.Length { if a[index] > a[i] {i:= index;} index := index + 1; } }
method FindMax(a: array<int>) returns (i: int) // Annotate this method with pre- and postconditions // that ensure it behaves as described. requires a.Length > 0 ensures 0<= i < a.Length ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i] { // Fill in the body that calculates the INDEX of the maximum. i := 0; var index := 1; while index < a.Length invariant 0 < index <= a.Length invariant 0 <= i < index invariant forall k :: 0 <= k < index ==> a[k] <= a[i] { if a[index] > a[i] {i:= index;} index := index + 1; } }
Dafny-experiences_tmp_tmp150sm9qy_dafny_started_tutorial_dafny_tutorial_array.dfy
114
114
Dafny program: 114
/* Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. */ predicate sorted_between(A:array<int>, from:int, to:int) reads A { forall i, j :: 0 <= i <= j < A.Length && from <= i <= j <= to ==> A[i] <= A[j] } predicate sorted(A:array<int>) reads A { sorted_between(A, 0, A.Length-1) } method BubbleSort(A:array<int>) modifies A ensures sorted(A) ensures multiset(A[..]) == multiset(old(A[..])) { var N := A.Length; var i := N-1; while 0 < i { print A[..], "\n"; var j := 0; while j < i { if A[j] > A[j+1] { A[j], A[j+1] := A[j+1], A[j]; print A[..], "\n"; } j := j+1; } i := i-1; print "\n"; } } method Main() { var A := new int[10]; A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[8], A[9] := 2, 4, 6, 15, 3, 19, 17, 16, 18, 1; BubbleSort(A); print A[..]; } /* Explanation: // A is ordered for each pair of elements such that // the first element belongs to the left partition of i // and the second element belongs to the right partition of i // There is a variable defined by the value that the array takes at position j // Therefore, each value that the array takes for all elements from 0 to j // They are less than or equal to the value of the variable */
/* Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. */ predicate sorted_between(A:array<int>, from:int, to:int) reads A { forall i, j :: 0 <= i <= j < A.Length && from <= i <= j <= to ==> A[i] <= A[j] } predicate sorted(A:array<int>) reads A { sorted_between(A, 0, A.Length-1) } method BubbleSort(A:array<int>) modifies A ensures sorted(A) ensures multiset(A[..]) == multiset(old(A[..])) { var N := A.Length; var i := N-1; while 0 < i invariant multiset(A[..]) == multiset(old(A[..])) invariant sorted_between(A, i, N-1) invariant forall n, m :: 0 <= n <= i < m < N ==> A[n] <= A[m] decreases i { print A[..], "\n"; var j := 0; while j < i invariant 0 < i < N invariant 0 <= j <= i invariant multiset(A[..]) == multiset(old(A[..])) invariant sorted_between(A, i, N-1) invariant forall n, m :: 0 <= n <= i < m < N ==> A[n] <= A[m] invariant forall n :: 0 <= n <= j ==> A[n] <= A[j] decreases i - j { if A[j] > A[j+1] { A[j], A[j+1] := A[j+1], A[j]; print A[..], "\n"; } j := j+1; } i := i-1; print "\n"; } } method Main() { var A := new int[10]; A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[8], A[9] := 2, 4, 6, 15, 3, 19, 17, 16, 18, 1; BubbleSort(A); print A[..]; } /* Explanation: invariant forall n, m :: 0 <= n <= i <m <N ==> A [n] <= A [m] // A is ordered for each pair of elements such that // the first element belongs to the left partition of i // and the second element belongs to the right partition of i invariant forall n :: 0 <= n <= j ==> A [n] <= A [j] // There is a variable defined by the value that the array takes at position j // Therefore, each value that the array takes for all elements from 0 to j // They are less than or equal to the value of the variable */
Dafny-programs_tmp_tmpnso9eu7u_Algorithms + sorting_bubble-sort.dfy
115
115
Dafny program: 115
method addArrays(a : array<int>, b : array<int>) returns (c : array<int>) requires a.Length == b.Length ensures b.Length == c.Length ensures forall i:int :: 0 <= i <c.Length ==> c[i] == a[i] + b[i] { c := new int[a.Length]; var j := 0; while (j < a.Length) { c[j] := a[j] + b[j]; j := j + 1; } }
method addArrays(a : array<int>, b : array<int>) returns (c : array<int>) requires a.Length == b.Length ensures b.Length == c.Length ensures forall i:int :: 0 <= i <c.Length ==> c[i] == a[i] + b[i] { c := new int[a.Length]; var j := 0; while (j < a.Length) invariant 0 <= j <= c.Length invariant forall i :: (0 <= i < j) ==> c[i] == a[i] + b[i]; { c[j] := a[j] + b[j]; j := j + 1; } }
DafnyExercises_tmp_tmpd6qyevja_Part1_Q1.dfy
117
117
Dafny program: 117
/** Consider cellular automata: a row of cells is repeatedly updated according to a rule. In this exercise I dabbled with, each cell has the value either false or true. Each cell's next state depends only on the immediate neighbours, in the case where the cell is at the edges of the row, the inexistent neighbours are replaced by "false". The automaton table will contain the initial row, plus a row for each number of steps. */ class Automaton { /** This method computes the automaton. Provide the initial row: init, the rule and the desired number of steps */ method ExecuteAutomaton(init: seq<bool>, rule: (bool, bool, bool) -> bool, steps: nat) returns (table: seq<seq<bool>>) // we need the initial row to have the length bigger or equal to two requires |init| >= 2 // after computation the automaton is made of the initial row plus a row for each of the steps ensures |table| == 1 + steps // the automaton must have the initial row at the top ensures table[0] == init; // all rows in the automaton must be the same length ensures forall i | 0 <= i < |table| :: |table[i]| == |init| // all the middle row elements (with existing neighbours) after a step, will be equal to the rule applied on the element in the previous state // and its neigbours ensures forall i | 0 <= i < |table| - 1 :: forall j | 1 <= j <= |table[i]| - 2 :: table[i + 1][j] == rule(table[i][j - 1], table[i][j], table[i][j + 1]) // the corner row elements (with non-existing neighbours) after a step, will be equal to the rule applied on the element in the previous state, // its neighbour and false ensures forall i | 0 <= i < |table| - 1 :: table[i + 1][0] == rule(false, table[i][0], table[i][1]) && table[i + 1][|table[i]| - 1] == rule(table[i][|table[i]| - 2], table[i][|table[i]| - 1], false) { // the table containing the automaton var result : seq<seq<bool>> := [init]; // the current row var currentSeq := init; var index := 0; while index < steps // the length of the table will be the index + 1, since it starts with an element and at every loop iteration we add a row to it // the first element of the table is the init row // the lenght of the rows in the table are equal // Dafny needs mentioning that that the currentSeq is equal to the element at position index in the table // invariant for the first ensures condition obtained by replacing constant with variable forall j | 1 <= j <= |result[i]| - 2 :: result[i + 1][j] == rule(result[i][j - 1], result[i][j], result[i][j + 1]) // invariant for the second ensures condition obtained by replacing constant with variable result[i + 1][0] == rule(false, result[i][0], result[i][1]) && result[i + 1][|result[i]| - 1] == rule(result[i][|result[i]| - 2], result[i][|result[i]| - 1], false) // the decreases clause to prove termination of this loop { var index2 := 1; // the next row to be computed var nextSeq := []; nextSeq := nextSeq + [rule(false, currentSeq[0], currentSeq[1])]; while index2 < |currentSeq| - 1 // even though its trivial, Dafny needs mentioning that the below invariant holds at every iteration of the loop, // since nextSeq[0] was initialized before entering the loop // all elements smaller than index2 are already present in the new row with the value calculated by the rule, // the element at index2 is still to be computed inside the while loop, thus when entering the loop // the rule value does not yet hold for it { nextSeq := nextSeq + [rule(currentSeq[index2 - 1], currentSeq[index2], currentSeq[index2 + 1])]; index2 := index2 + 1; } nextSeq := nextSeq + [rule(currentSeq[|currentSeq| - 2], currentSeq[|currentSeq| - 1], false)]; currentSeq := nextSeq; result := result + [nextSeq]; index := index + 1; } return result; } // example rule function TheRule(a: bool, b: bool, c: bool) : bool { a || b || c } // example rule 2 function TheRule2(a: bool, b: bool, c: bool) : bool { a && b && c } method testMethod() { // the initial row var init := [false, false, true, false, false]; // calculate automaton steps with var result := ExecuteAutomaton(init, TheRule, 3); // the intial row plus the three steps of the automaton are showed bellow var result2 := ExecuteAutomaton(init, TheRule2, 2); // the intial row plus the two steps of the automaton are showed bellow } }
/** Consider cellular automata: a row of cells is repeatedly updated according to a rule. In this exercise I dabbled with, each cell has the value either false or true. Each cell's next state depends only on the immediate neighbours, in the case where the cell is at the edges of the row, the inexistent neighbours are replaced by "false". The automaton table will contain the initial row, plus a row for each number of steps. */ class Automaton { /** This method computes the automaton. Provide the initial row: init, the rule and the desired number of steps */ method ExecuteAutomaton(init: seq<bool>, rule: (bool, bool, bool) -> bool, steps: nat) returns (table: seq<seq<bool>>) // we need the initial row to have the length bigger or equal to two requires |init| >= 2 // after computation the automaton is made of the initial row plus a row for each of the steps ensures |table| == 1 + steps // the automaton must have the initial row at the top ensures table[0] == init; // all rows in the automaton must be the same length ensures forall i | 0 <= i < |table| :: |table[i]| == |init| // all the middle row elements (with existing neighbours) after a step, will be equal to the rule applied on the element in the previous state // and its neigbours ensures forall i | 0 <= i < |table| - 1 :: forall j | 1 <= j <= |table[i]| - 2 :: table[i + 1][j] == rule(table[i][j - 1], table[i][j], table[i][j + 1]) // the corner row elements (with non-existing neighbours) after a step, will be equal to the rule applied on the element in the previous state, // its neighbour and false ensures forall i | 0 <= i < |table| - 1 :: table[i + 1][0] == rule(false, table[i][0], table[i][1]) && table[i + 1][|table[i]| - 1] == rule(table[i][|table[i]| - 2], table[i][|table[i]| - 1], false) { // the table containing the automaton var result : seq<seq<bool>> := [init]; // the current row var currentSeq := init; var index := 0; while index < steps invariant 0 <= index <= steps // the length of the table will be the index + 1, since it starts with an element and at every loop iteration we add a row to it invariant |result| == index + 1 // the first element of the table is the init row invariant result[0] == init // the lenght of the rows in the table are equal invariant |currentSeq| == |init| invariant forall i | 0 <= i < |result| :: |result[i]| == |init| // Dafny needs mentioning that that the currentSeq is equal to the element at position index in the table invariant currentSeq == result[index] // invariant for the first ensures condition obtained by replacing constant with variable invariant forall i | 0 <= i < |result| - 1 :: forall j | 1 <= j <= |result[i]| - 2 :: result[i + 1][j] == rule(result[i][j - 1], result[i][j], result[i][j + 1]) // invariant for the second ensures condition obtained by replacing constant with variable invariant forall i | 0 <= i < |result| - 1 :: result[i + 1][0] == rule(false, result[i][0], result[i][1]) && result[i + 1][|result[i]| - 1] == rule(result[i][|result[i]| - 2], result[i][|result[i]| - 1], false) // the decreases clause to prove termination of this loop decreases steps - index { var index2 := 1; // the next row to be computed var nextSeq := []; nextSeq := nextSeq + [rule(false, currentSeq[0], currentSeq[1])]; while index2 < |currentSeq| - 1 invariant |currentSeq| == |init| invariant 0 <= index2 <= |currentSeq| - 1 invariant |nextSeq| == index2 // even though its trivial, Dafny needs mentioning that the below invariant holds at every iteration of the loop, // since nextSeq[0] was initialized before entering the loop invariant nextSeq[0] == rule(false, currentSeq[0], currentSeq[1]) // all elements smaller than index2 are already present in the new row with the value calculated by the rule, // the element at index2 is still to be computed inside the while loop, thus when entering the loop // the rule value does not yet hold for it invariant forall i | 1 <= i < index2 :: nextSeq[i] == rule(currentSeq[i - 1], currentSeq[i], currentSeq[i + 1]) decreases |currentSeq| - index2 { nextSeq := nextSeq + [rule(currentSeq[index2 - 1], currentSeq[index2], currentSeq[index2 + 1])]; index2 := index2 + 1; } nextSeq := nextSeq + [rule(currentSeq[|currentSeq| - 2], currentSeq[|currentSeq| - 1], false)]; currentSeq := nextSeq; result := result + [nextSeq]; index := index + 1; } return result; } // example rule function TheRule(a: bool, b: bool, c: bool) : bool { a || b || c } // example rule 2 function TheRule2(a: bool, b: bool, c: bool) : bool { a && b && c } method testMethod() { // the initial row var init := [false, false, true, false, false]; // calculate automaton steps with var result := ExecuteAutomaton(init, TheRule, 3); // the intial row plus the three steps of the automaton are showed bellow assert(result[0] == [false, false, true, false, false]); // the initial state of the automaton assert(result[1] == [false, true, true, true, false]); // after the first step assert(result[2] == [true, true, true, true, true]); // after the second step assert(result[3] == [true, true, true, true, true]); // after the third step, remains the same from now on var result2 := ExecuteAutomaton(init, TheRule2, 2); // the intial row plus the two steps of the automaton are showed bellow assert(result2[0] == [false, false, true, false, false]); // the initial state of the automaton assert(result2[1] == [false, false, false, false, false]); // after the first step assert(result2[2] == [false, false, false, false, false]); // after the second step, remains the same from now on } }
DafnyPrograms_tmp_tmp74_f9k_c_automaton.dfy
118
118
Dafny program: 118
/** Inverts an array of ints. */ method InvertArray(a: array<int>) modifies a ensures forall i | 0 <= i < a.Length :: a[i] == old(a[a.Length-1-i]) { var index := 0; while index < a.Length / 2 // the elements i before position index are already switched with the old value of position a.Length - 1 - i // the elements of form a.Length - 1 - i after position a.Length - 1 - index are already switched with the old value of position i // the elements between index and a.Length - index are unchanged : the middle of the array { a[index], a[a.Length - 1 - index] := a[a.Length - 1 - index], a[index]; index := index + 1; } }
/** Inverts an array of ints. */ method InvertArray(a: array<int>) modifies a ensures forall i | 0 <= i < a.Length :: a[i] == old(a[a.Length-1-i]) { var index := 0; while index < a.Length / 2 invariant 0 <= index <= a.Length / 2 // the elements i before position index are already switched with the old value of position a.Length - 1 - i invariant forall i | 0 <= i < index :: a[i] == old(a[a.Length - 1 - i]) // the elements of form a.Length - 1 - i after position a.Length - 1 - index are already switched with the old value of position i invariant forall i | 0 <= i < index :: a[a.Length - 1 - i] == old(a[i]) // the elements between index and a.Length - index are unchanged : the middle of the array invariant forall i | index <= i < a.Length - index :: a[i] == old(a[i]) { a[index], a[a.Length - 1 - index] := a[a.Length - 1 - index], a[index]; index := index + 1; } }
DafnyPrograms_tmp_tmp74_f9k_c_invertarray.dfy
119
119
Dafny program: 119
/** This ADT represents a multiset. */ trait MyMultiset { // internal invariant ghost predicate Valid() reads this // abstract variable ghost var theMultiset: multiset<int> method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() ensures theMultiset == old(theMultiset) + multiset{elem} ensures didChange ghost predicate Contains(elem: int) reads this { elem in theMultiset } method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange method Length() returns (len: int) requires Valid() ensures Valid() ensures len == |theMultiset| method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset } /** This implementation implements the ADT with a map. */ class MultisetImplementationWithMap extends MyMultiset { // valid invariant predicate of the ADT implementation ghost predicate Valid() reads this { (forall i | i in elements.Keys :: elements[i] > 0) && (theMultiset == A(elements)) && (forall i :: i in elements.Keys <==> Contains(i)) } // the abstraction function function A(m: map<int, nat>): (s:multiset<int>) ensures (forall i | i in m :: m[i] == A(m)[i]) && (m == map[] <==> A(m) == multiset{}) && (forall i :: i in m <==> i in A(m)) // lemma for the opposite of the abstraction function lemma LemmaReverseA(m: map<int, nat>, s : seq<int>) requires (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) ensures A(m) == multiset(s) // ADT concrete implementation variable var elements: map<int, nat>; // constructor of the implementation class that ensures the implementation invariant constructor MultisetImplementationWithMap() ensures Valid() ensures elements == map[] ensures theMultiset == multiset{} { elements := map[]; theMultiset := multiset{}; } //adds an element to the multiset method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures elem in elements ==> elements == elements[elem := elements[elem]] ensures theMultiset == old(theMultiset) + multiset{elem} ensures !(elem in elements) ==> elements == elements[elem := 1] ensures didChange ensures Contains(elem) ensures Valid() { if !(elem in elements) { elements := elements[elem := 1]; } else { elements := elements[elem := (elements[elem] + 1)]; } didChange := true; theMultiset := A(elements); } //removes an element from the multiset method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange ensures didChange <==> elements != old(elements) { /* If the multiset does not contain the element */ if elem !in elements { return false; } /* If the multiset contains the element */ elements := elements[elem := elements[elem] - 1]; if(elements[elem] == 0) { elements := elements - {elem}; } theMultiset := A(elements); didChange := true; } //gets the length of the multiset method Length() returns (len: int) requires Valid() ensures len == |theMultiset| { var result := Map2Seq(elements); return |result|; } //compares the current multiset with another multiset and determines if they're equal method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset { var otherMapSeq := other.getElems(); var c := this.getElems(); return multiset(c) == multiset(otherMapSeq); } //gets the elements of the multiset as a sequence method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset { var result : seq<int>; result := Map2Seq(elements); return result; } //Transforms a map to a sequence method Map2Seq(m: map<int, nat>) returns (s: seq<int>) requires forall i | i in m.Keys :: i in m.Keys <==> m[i] > 0 ensures forall i | i in m.Keys :: multiset(s)[i] == m[i] ensures forall i | i in m.Keys :: i in s ensures A(m) == multiset(s) ensures (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) { if |m| == 0 {return []; } var keys := m.Keys; var key: int; s := []; while keys != {} { key :| key in keys; var counter := 0; while counter < m[key] { s := s + [key]; counter := counter + 1; } keys := keys - {key}; } LemmaReverseA(m, s); } method Test1() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); //declaring the other bag var theOtherBag : MultisetImplementationWithMap; theOtherBag := new MultisetImplementationWithMap.MultisetImplementationWithMap(); // equals test - unequal bags var b:= this.equals(theOtherBag); // equals test - equal bags theOtherBag.theMultiset := multiset{1, 2, 3, 4}; theOtherBag.elements := map[1 := 1, 2:=1, 3:=1,4:=1]; var c:= this.equals(theOtherBag); } method Test2() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); //add test var d := this.Add(3); var e := this.getElems(); //remove test var f := this.Remove(4); var g := this.getElems(); //length test var h := this.Length(); } method Test3() { //test Map2Seq var m := map[2:= 2, 3:=3, 4:= 4]; var s :seq<int> := [2, 2, 3, 3, 3, 4, 4,4 ,4]; var a := this.Map2Seq(m); var x := map[1 := 1, 2:= 1, 3:= 1]; var y :seq<int> := [1, 2, 3]; var z := this.Map2Seq(x); } }
/** This ADT represents a multiset. */ trait MyMultiset { // internal invariant ghost predicate Valid() reads this // abstract variable ghost var theMultiset: multiset<int> method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() ensures theMultiset == old(theMultiset) + multiset{elem} ensures didChange ghost predicate Contains(elem: int) reads this { elem in theMultiset } method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange method Length() returns (len: int) requires Valid() ensures Valid() ensures len == |theMultiset| method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset } /** This implementation implements the ADT with a map. */ class MultisetImplementationWithMap extends MyMultiset { // valid invariant predicate of the ADT implementation ghost predicate Valid() reads this { (forall i | i in elements.Keys :: elements[i] > 0) && (theMultiset == A(elements)) && (forall i :: i in elements.Keys <==> Contains(i)) } // the abstraction function function A(m: map<int, nat>): (s:multiset<int>) ensures (forall i | i in m :: m[i] == A(m)[i]) && (m == map[] <==> A(m) == multiset{}) && (forall i :: i in m <==> i in A(m)) // lemma for the opposite of the abstraction function lemma LemmaReverseA(m: map<int, nat>, s : seq<int>) requires (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) ensures A(m) == multiset(s) // ADT concrete implementation variable var elements: map<int, nat>; // constructor of the implementation class that ensures the implementation invariant constructor MultisetImplementationWithMap() ensures Valid() ensures elements == map[] ensures theMultiset == multiset{} { elements := map[]; theMultiset := multiset{}; } //adds an element to the multiset method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures elem in elements ==> elements == elements[elem := elements[elem]] ensures theMultiset == old(theMultiset) + multiset{elem} ensures !(elem in elements) ==> elements == elements[elem := 1] ensures didChange ensures Contains(elem) ensures Valid() { if !(elem in elements) { elements := elements[elem := 1]; } else { elements := elements[elem := (elements[elem] + 1)]; } didChange := true; theMultiset := A(elements); } //removes an element from the multiset method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange ensures didChange <==> elements != old(elements) { /* If the multiset does not contain the element */ if elem !in elements { assert ! Contains(elem); assert theMultiset == old(theMultiset); assert Valid(); return false; } /* If the multiset contains the element */ assert Contains(elem); elements := elements[elem := elements[elem] - 1]; if(elements[elem] == 0) { elements := elements - {elem}; } theMultiset := A(elements); didChange := true; } //gets the length of the multiset method Length() returns (len: int) requires Valid() ensures len == |theMultiset| { var result := Map2Seq(elements); return |result|; } //compares the current multiset with another multiset and determines if they're equal method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset { var otherMapSeq := other.getElems(); assert multiset(otherMapSeq) == other.theMultiset; var c := this.getElems(); return multiset(c) == multiset(otherMapSeq); } //gets the elements of the multiset as a sequence method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset { var result : seq<int>; result := Map2Seq(elements); return result; } //Transforms a map to a sequence method Map2Seq(m: map<int, nat>) returns (s: seq<int>) requires forall i | i in m.Keys :: i in m.Keys <==> m[i] > 0 ensures forall i | i in m.Keys :: multiset(s)[i] == m[i] ensures forall i | i in m.Keys :: i in s ensures A(m) == multiset(s) ensures (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) { if |m| == 0 {return []; } var keys := m.Keys; var key: int; s := []; while keys != {} invariant forall i | i in m.Keys :: i in keys <==> multiset(s)[i] == 0 invariant forall i | i in m.Keys - keys :: multiset(s)[i] == m[i] { key :| key in keys; var counter := 0; while counter < m[key] invariant 0 <= counter <= m[key] invariant multiset(s)[key] == counter invariant forall i | i in m.Keys && i != key :: i in keys <==> multiset(s)[i] == 0 invariant forall i | i in m.Keys - keys :: multiset(s)[i] == m[i]; { s := s + [key]; counter := counter + 1; } keys := keys - {key}; } LemmaReverseA(m, s); } method Test1() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); assert multiset(a) == multiset{1, 2, 3, 4}; //declaring the other bag var theOtherBag : MultisetImplementationWithMap; theOtherBag := new MultisetImplementationWithMap.MultisetImplementationWithMap(); // equals test - unequal bags var b:= this.equals(theOtherBag); assert b == false; // equals test - equal bags theOtherBag.theMultiset := multiset{1, 2, 3, 4}; theOtherBag.elements := map[1 := 1, 2:=1, 3:=1,4:=1]; var c:= this.equals(theOtherBag); assert c == true; } method Test2() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); assert multiset(a) == multiset{1, 2, 3, 4}; //add test var d := this.Add(3); var e := this.getElems(); assert multiset(e) == multiset([1, 2, 3, 4, 3]); //remove test var f := this.Remove(4); var g := this.getElems(); assert multiset(g) == multiset([1, 2, 3, 3]); //length test var h := this.Length(); assert h == 4; } method Test3() { //test Map2Seq var m := map[2:= 2, 3:=3, 4:= 4]; var s :seq<int> := [2, 2, 3, 3, 3, 4, 4,4 ,4]; var a := this.Map2Seq(m); assert multiset(a) == multiset(s); var x := map[1 := 1, 2:= 1, 3:= 1]; var y :seq<int> := [1, 2, 3]; var z := this.Map2Seq(x); assert multiset(z) == multiset(y); } }
DafnyPrograms_tmp_tmp74_f9k_c_map-multiset-implementation.dfy
120
120
Dafny program: 120
//predicate for primeness ghost predicate prime(n: nat) { n > 1 && (forall nr | 1 < nr < n :: n % nr != 0) } datatype Answer = Yes | No | Unknown //the class containing a prime database, if a number is prime it returns Yes, if it is not No and if the number //is not in the database it returns Unknown class {:autocontracts} PrimeMap{ var database: map<nat, bool>; //the valid invariant of the class ghost predicate Valid() reads this { forall i | i in database.Keys :: (database[i] == true <==> prime(i)) } //the constructor constructor() ensures database == map[] { database := map[]; } // insert an already known prime number into the database method InsertPrime(n: nat) modifies this; ensures database.Keys == old(database.Keys) + {n} requires prime(n) ensures database == database[n := true] { database := database[n := true]; } // check the primeness of n and insert it accordingly into the database method InsertNumber(n: nat) modifies this ensures database.Keys == old(database.Keys) + {n} ensures prime(n) <==> database == database[n := true] ensures !prime(n) <==> database == database[n := false] { var prime : bool; prime := testPrimeness(n); database := database[n := prime]; } // lookup n in the database and reply with Yes or No if it's in the database and it is or it is not prime, // or with Unknown when it's not in the databse method IsPrime?(n: nat) returns (answer: Answer) ensures database.Keys == old(database.Keys) ensures (n in database) && prime(n) <==> answer == Yes ensures (n in database) && !prime(n) <==> answer == No ensures !(n in database) <==> answer == Unknown { if !(n in database){ return Unknown; } else if database[n] == true { return Yes; } else if database[n] == false { return No; } } // method to test whether a number is prime, returns bool method testPrimeness(n: nat) returns (result: bool) requires n >= 0 ensures result <==> prime(n) { if n == 0 || n == 1{ return false; } var i := 2; result := true; while i < n { if n % i == 0 { result := false; } i := i + 1; } } } method testingMethod() { // witness to prove to dafny (exists nr | 1 < nr < n :: n % nr != 0), since // the !(forall nr | 1 < nr < n :: n % nr != 0) from !prime predicate ==> (exists nr | 1 < nr < n :: n % nr == 0) var pm := new PrimeMap(); // InsertPrime test pm.InsertPrime(13); // InsertNumber test pm.InsertNumber(17); pm.InsertNumber(15); var result: Answer := pm.IsPrime?(17); var result2: Answer := pm.IsPrime?(15); var result3: Answer := pm.IsPrime?(454); var result4: Answer := pm.IsPrime?(13); }
//predicate for primeness ghost predicate prime(n: nat) { n > 1 && (forall nr | 1 < nr < n :: n % nr != 0) } datatype Answer = Yes | No | Unknown //the class containing a prime database, if a number is prime it returns Yes, if it is not No and if the number //is not in the database it returns Unknown class {:autocontracts} PrimeMap{ var database: map<nat, bool>; //the valid invariant of the class ghost predicate Valid() reads this { forall i | i in database.Keys :: (database[i] == true <==> prime(i)) } //the constructor constructor() ensures database == map[] { database := map[]; } // insert an already known prime number into the database method InsertPrime(n: nat) modifies this; ensures database.Keys == old(database.Keys) + {n} requires prime(n) ensures database == database[n := true] { database := database[n := true]; } // check the primeness of n and insert it accordingly into the database method InsertNumber(n: nat) modifies this ensures database.Keys == old(database.Keys) + {n} ensures prime(n) <==> database == database[n := true] ensures !prime(n) <==> database == database[n := false] { var prime : bool; prime := testPrimeness(n); database := database[n := prime]; } // lookup n in the database and reply with Yes or No if it's in the database and it is or it is not prime, // or with Unknown when it's not in the databse method IsPrime?(n: nat) returns (answer: Answer) ensures database.Keys == old(database.Keys) ensures (n in database) && prime(n) <==> answer == Yes ensures (n in database) && !prime(n) <==> answer == No ensures !(n in database) <==> answer == Unknown { if !(n in database){ return Unknown; } else if database[n] == true { return Yes; } else if database[n] == false { return No; } } // method to test whether a number is prime, returns bool method testPrimeness(n: nat) returns (result: bool) requires n >= 0 ensures result <==> prime(n) { if n == 0 || n == 1{ return false; } var i := 2; result := true; while i < n invariant i >= 2 && i <= n invariant result <==> (forall j | 1 < j <= i - 1 :: n % j != 0) { if n % i == 0 { result := false; } i := i + 1; } } } method testingMethod() { // witness to prove to dafny (exists nr | 1 < nr < n :: n % nr != 0), since // the !(forall nr | 1 < nr < n :: n % nr != 0) from !prime predicate ==> (exists nr | 1 < nr < n :: n % nr == 0) assert !(forall nr | 1 < nr < 15 :: 15 % nr != 0) ==> (exists nr | 1 < nr < 15 :: 15 % nr == 0); assert 15 % 3 == 0; assert(exists nr | 1 < nr < 15 :: 15 % nr == 0); var pm := new PrimeMap(); // InsertPrime test pm.InsertPrime(13); // InsertNumber test pm.InsertNumber(17); pm.InsertNumber(15); assert pm.database.Keys == {17, 15, 13}; var result: Answer := pm.IsPrime?(17); assert result == Yes; var result2: Answer := pm.IsPrime?(15); assert result2 == No; var result3: Answer := pm.IsPrime?(454); assert result3 == Unknown; var result4: Answer := pm.IsPrime?(13); assert result4 == Yes; }
DafnyPrograms_tmp_tmp74_f9k_c_prime-database.dfy
121
121
Dafny program: 121
/* * Formal specification and verification of a dynamic programming algorithm for calculating C(n, k). * FEUP, MIEIC, MFES, 2020/21. */ // Initial recursive definition of C(n, k), based on the Pascal equality. function comb(n: nat, k: nat): nat requires 0 <= k <= n { if k == 0 || k == n then 1 else comb(n-1, k) + comb(n-1, k-1) } by method // Calculates C(n,k) iteratively in time O(k*(n-k)) and space O(n-k), // with dynamic programming. { var maxj := n - k; var c := new nat[1 + maxj]; forall i | 0 <= i <= maxj { c[i] := 1; } var i := 1; while i <= k { var j := 1; while j <= maxj { c[j] := c[j] + c[j-1]; j := j+1; } i := i + 1; } return c[maxj]; } lemma combProps(n: nat, k: nat) requires 0 <= k <= n ensures comb(n, k) == comb(n, n-k) {} method Main() { // Statically checked (proved) test cases! var res1 := comb(40, 10); print "combDyn(40, 10) = ", res1, "\n"; } method testComb() { }
/* * Formal specification and verification of a dynamic programming algorithm for calculating C(n, k). * FEUP, MIEIC, MFES, 2020/21. */ // Initial recursive definition of C(n, k), based on the Pascal equality. function comb(n: nat, k: nat): nat requires 0 <= k <= n { if k == 0 || k == n then 1 else comb(n-1, k) + comb(n-1, k-1) } by method // Calculates C(n,k) iteratively in time O(k*(n-k)) and space O(n-k), // with dynamic programming. { var maxj := n - k; var c := new nat[1 + maxj]; forall i | 0 <= i <= maxj { c[i] := 1; } var i := 1; while i <= k invariant 1 <= i <= k + 1 invariant forall j :: 0 <= j <= maxj ==> c[j] == comb(j + i - 1, i - 1) { var j := 1; while j <= maxj invariant 1 <= j <= maxj + 1 invariant forall j' :: 0 <= j' < j ==> c[j'] == comb(j' + i, i) invariant forall j' :: j <= j' <= maxj ==> c[j'] == comb(j' + i - 1, i - 1) { c[j] := c[j] + c[j-1]; j := j+1; } i := i + 1; } return c[maxj]; } lemma combProps(n: nat, k: nat) requires 0 <= k <= n ensures comb(n, k) == comb(n, n-k) {} method Main() { // Statically checked (proved) test cases! assert comb(5, 2) == 10; assert comb(5, 0) == 1; assert comb(5, 5) == 1; assert comb(5, 2) == 10; var res1 := comb(40, 10); print "combDyn(40, 10) = ", res1, "\n"; } method testComb() { assert comb(6, 2) == 15; assert comb(6, 3) == 20; assert comb(6, 4) == 15; assert comb(6, 6) == 1; }
DafnyProjects_tmp_tmp2acw_s4s_CombNK.dfy
123
123
Dafny program: 123
/* * Formal verification of an O(log n) algorithm to calculate the natural power of a real number (x^n), * illustrating the usage of lemmas and automatic induction in Dafny. * J. Pascoal Faria, FEUP, Jan/2022. */ // Recursive definition of x^n in functional style, with time and space complexity O(n). function power(x: real, n: nat) : real { if n == 0 then 1.0 else x * power(x, n-1) } // Computation of x^n in time and space O(log n). method powerDC(x: real, n: nat) returns (p : real) ensures p == power(x, n) { if n == 0 { return 1.0; } else if n == 1 { return x; } else if n % 2 == 0 { productOfPowers(x, n/2, n/2); // recall lemma var temp := powerDC(x, n/2); return temp * temp; } else { productOfPowers(x, (n-1)/2, (n-1)/2); // recall lemma var temp := powerDC(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that the method power takes advantage of. // The property is proved by automatic induction on 'a'. lemma {:induction a} productOfPowers(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { } // A few test cases (checked statically by Dafny). method testPowerDC() { var p1 := powerDC( 2.0, 5); assert p1 == 32.0; var p2 := powerDC(-2.0, 2); assert p2 == 4.0; var p3 := powerDC(-2.0, 1); assert p3 == -2.0; var p4 := powerDC(-2.0, 0); assert p4 == 1.0; var p5 := powerDC( 0.0, 0); assert p5 == 1.0; }
/* * Formal verification of an O(log n) algorithm to calculate the natural power of a real number (x^n), * illustrating the usage of lemmas and automatic induction in Dafny. * J. Pascoal Faria, FEUP, Jan/2022. */ // Recursive definition of x^n in functional style, with time and space complexity O(n). function power(x: real, n: nat) : real { if n == 0 then 1.0 else x * power(x, n-1) } // Computation of x^n in time and space O(log n). method powerDC(x: real, n: nat) returns (p : real) ensures p == power(x, n) { if n == 0 { return 1.0; } else if n == 1 { return x; } else if n % 2 == 0 { productOfPowers(x, n/2, n/2); // recall lemma var temp := powerDC(x, n/2); return temp * temp; } else { productOfPowers(x, (n-1)/2, (n-1)/2); // recall lemma var temp := powerDC(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that the method power takes advantage of. // The property is proved by automatic induction on 'a'. lemma {:induction a} productOfPowers(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { } // A few test cases (checked statically by Dafny). method testPowerDC() { var p1 := powerDC( 2.0, 5); assert p1 == 32.0; var p2 := powerDC(-2.0, 2); assert p2 == 4.0; var p3 := powerDC(-2.0, 1); assert p3 == -2.0; var p4 := powerDC(-2.0, 0); assert p4 == 1.0; var p5 := powerDC( 0.0, 0); assert p5 == 1.0; }
DafnyProjects_tmp_tmp2acw_s4s_Power.dfy
124
124
Dafny program: 124
/** * Proves the correctness of a "raw" array sorting algorithm that swaps elements out of order, chosen randomly. * FEUP, MFES, 2020/21. */ // Type of each array element; can be any type supporting comparision operators. type T = int // Checks if array 'a' is sorted by non-descending order. ghost predicate sorted(a: array<T>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Obtains the set of all inversions in an array 'a', i.e., // the pairs of indices i, j such that i < j and a[i] > a[j]. ghost function inversions(a: array<T>): set<(nat, nat)> reads a { set i, j | 0 <= i < j < a.Length && a[i] > a[j] :: (i, j) } // Sorts an array by simply swapping elements out of order, chosen randomly. method rawsort(a: array<T>) modifies a ensures sorted(a) && multiset(a[..]) == multiset(old(a[..])) { if i, j :| 0 <= i < j < a.Length && a[i] > a[j] { ghost var bef := inversions(a); // inversions before swapping a[i], a[j] := a[j], a[i]; // swap ghost var aft := inversions(a); // inversions after swapping ghost var aft2bef := map p | p in aft :: // maps inversions in 'aft' to 'bef' (if p.0 == i && p.1 > j then j else if p.0 == j then i else p.0, if p.1 == i then j else if p.1 == j && p.0 < i then i else p.1); mappingProp(aft, bef, (i, j), aft2bef); // recall property implying |aft| < |bef| rawsort(a); // proceed recursivelly } } // States and proves (by induction) the following property: given sets 'a' and 'b' and an injective // and non-surjective mapping 'm' from elements in 'a' to elements in 'b', then |a| < |b|. // To facilitate the proof, it is given an element 'k' in 'b' that is not an image of elements in 'a'. lemma mappingProp<T1, T2>(a: set<T1>, b: set<T2>, k: T2, m: map<T1, T2>) requires k in b requires forall x :: x in a ==> x in m && m[x] in b - {k} requires forall x, y :: x in a && y in a && x != y ==> m[x] != m[y] ensures |a| < |b| { if x :| x in a { mappingProp(a - {x}, b - {m[x]}, k, m); } } method testRawsort() { var a : array<T> := new T[] [3, 5, 1]; rawsort(a); }
/** * Proves the correctness of a "raw" array sorting algorithm that swaps elements out of order, chosen randomly. * FEUP, MFES, 2020/21. */ // Type of each array element; can be any type supporting comparision operators. type T = int // Checks if array 'a' is sorted by non-descending order. ghost predicate sorted(a: array<T>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Obtains the set of all inversions in an array 'a', i.e., // the pairs of indices i, j such that i < j and a[i] > a[j]. ghost function inversions(a: array<T>): set<(nat, nat)> reads a { set i, j | 0 <= i < j < a.Length && a[i] > a[j] :: (i, j) } // Sorts an array by simply swapping elements out of order, chosen randomly. method rawsort(a: array<T>) modifies a ensures sorted(a) && multiset(a[..]) == multiset(old(a[..])) decreases |inversions(a)| { if i, j :| 0 <= i < j < a.Length && a[i] > a[j] { ghost var bef := inversions(a); // inversions before swapping a[i], a[j] := a[j], a[i]; // swap ghost var aft := inversions(a); // inversions after swapping ghost var aft2bef := map p | p in aft :: // maps inversions in 'aft' to 'bef' (if p.0 == i && p.1 > j then j else if p.0 == j then i else p.0, if p.1 == i then j else if p.1 == j && p.0 < i then i else p.1); mappingProp(aft, bef, (i, j), aft2bef); // recall property implying |aft| < |bef| rawsort(a); // proceed recursivelly } } // States and proves (by induction) the following property: given sets 'a' and 'b' and an injective // and non-surjective mapping 'm' from elements in 'a' to elements in 'b', then |a| < |b|. // To facilitate the proof, it is given an element 'k' in 'b' that is not an image of elements in 'a'. lemma mappingProp<T1, T2>(a: set<T1>, b: set<T2>, k: T2, m: map<T1, T2>) requires k in b requires forall x :: x in a ==> x in m && m[x] in b - {k} requires forall x, y :: x in a && y in a && x != y ==> m[x] != m[y] ensures |a| < |b| { if x :| x in a { mappingProp(a - {x}, b - {m[x]}, k, m); } } method testRawsort() { var a : array<T> := new T[] [3, 5, 1]; assert a[..] == [3, 5, 1]; rawsort(a); assert a[..] == [1, 3, 5]; }
DafnyProjects_tmp_tmp2acw_s4s_RawSort.dfy
125
125
Dafny program: 125
/* * Formal verification of a simple algorithm to find the maximum value in an array. * FEUP, MIEIC, MFES, 2020/21. */ // Finds the maximum value in a non-empty array. method findMax(a: array<real>) returns (max: real) requires a.Length > 0 ensures exists k :: 0 <= k < a.Length && max == a[k] ensures forall k :: 0 <= k < a.Length ==> max >= a[k] { max := a[0]; for i := 1 to a.Length { if (a[i] > max) { max := a[i]; } } } // Test cases checked statically. method testFindMax() { var a1 := new real[3] [1.0, 2.0, 3.0]; // sorted asc var m1 := findMax(a1); var a2 := new real[3] [3.0, 2.0, 1.0]; // sorted desc var m2 := findMax(a2); var a3 := new real[3] [2.0, 3.0, 1.0]; // unsorted var m3 := findMax(a3); var a4 := new real[3] [1.0, 2.0, 2.0]; // duplicates var m4 := findMax(a4); var a5 := new real[1] [1.0]; // single element var m5 := findMax(a5); var a6 := new real[3] [1.0, 1.0, 1.0]; // all equal var m6 := findMax(a6); }
/* * Formal verification of a simple algorithm to find the maximum value in an array. * FEUP, MIEIC, MFES, 2020/21. */ // Finds the maximum value in a non-empty array. method findMax(a: array<real>) returns (max: real) requires a.Length > 0 ensures exists k :: 0 <= k < a.Length && max == a[k] ensures forall k :: 0 <= k < a.Length ==> max >= a[k] { max := a[0]; for i := 1 to a.Length invariant exists k :: 0 <= k < i && max == a[k] invariant forall k :: 0 <= k < i ==> max >= a[k] { if (a[i] > max) { max := a[i]; } } } // Test cases checked statically. method testFindMax() { var a1 := new real[3] [1.0, 2.0, 3.0]; // sorted asc var m1 := findMax(a1); assert m1 == a1[2] == 3.0; var a2 := new real[3] [3.0, 2.0, 1.0]; // sorted desc var m2 := findMax(a2); assert m2 == a2[0] == 3.0; var a3 := new real[3] [2.0, 3.0, 1.0]; // unsorted var m3 := findMax(a3); assert m3 == a3[1] == 3.0; var a4 := new real[3] [1.0, 2.0, 2.0]; // duplicates var m4 := findMax(a4); assert m4 == a4[1] == 2.0; var a5 := new real[1] [1.0]; // single element var m5 := findMax(a5); assert m5 == a5[0] == 1.0; var a6 := new real[3] [1.0, 1.0, 1.0]; // all equal var m6 := findMax(a6); assert m6 == a6[0] == 1.0; }
DafnyProjects_tmp_tmp2acw_s4s_findMax.dfy
126
126
Dafny program: 126
// MFES, Exam 8/Sept/20201, Exercise 5 // Computes the length (i) of the longest common prefix (initial subarray) // of two arrays a and b. method longestPrefix(a: array<int>, b: array <int>) returns (i: nat) ensures i <= a.Length && i <= b.Length ensures a[..i] == b[..i] ensures i < a.Length && i < b.Length ==> a[i] != b[i] { i := 0; while i < a.Length && i < b.Length && a[i] == b[i] { i := i + 1; } } // Test method with an example. method testLongestPrefix() { var a := new int[] [1, 3, 2, 4, 8]; var b := new int[] [1, 3, 3, 4]; var i := longestPrefix(a, b); }
// MFES, Exam 8/Sept/20201, Exercise 5 // Computes the length (i) of the longest common prefix (initial subarray) // of two arrays a and b. method longestPrefix(a: array<int>, b: array <int>) returns (i: nat) ensures i <= a.Length && i <= b.Length ensures a[..i] == b[..i] ensures i < a.Length && i < b.Length ==> a[i] != b[i] { i := 0; while i < a.Length && i < b.Length && a[i] == b[i] invariant i <= a.Length && i <= b.Length invariant a[..i] == b[..i] { i := i + 1; } } // Test method with an example. method testLongestPrefix() { var a := new int[] [1, 3, 2, 4, 8]; var b := new int[] [1, 3, 3, 4]; var i := longestPrefix(a, b); assert a[2] != b[2]; // to help Dafny prove next assertion assert i == 2; }
DafnyProjects_tmp_tmp2acw_s4s_longestPrefix.dfy
127
127
Dafny program: 127
// Rearranges the elements in an array 'a' of natural numbers, // so that all odd numbers appear before all even numbers. method partitionOddEven(a: array<nat>) modifies a ensures multiset(a[..]) == multiset(old(a[..])) ensures ! exists i, j :: 0 <= i < j < a.Length && even(a[i]) && odd(a[j]) { var i := 0; // odd numbers are placed to the left of i var j := a.Length - 1; // even numbers are placed to the right of j while i <= j { if even(a[i]) && odd(a[j]) { a[i], a[j] := a[j], a[i]; } if odd(a[i]) { i := i + 1; } if even(a[j]) { j := j - 1; } } } predicate odd(n: nat) { n % 2 == 1 } predicate even(n: nat) { n % 2 == 0 } method testPartitionOddEven() { var a: array<nat> := new [] [1, 2, 3]; partitionOddEven(a); }
// Rearranges the elements in an array 'a' of natural numbers, // so that all odd numbers appear before all even numbers. method partitionOddEven(a: array<nat>) modifies a ensures multiset(a[..]) == multiset(old(a[..])) ensures ! exists i, j :: 0 <= i < j < a.Length && even(a[i]) && odd(a[j]) { var i := 0; // odd numbers are placed to the left of i var j := a.Length - 1; // even numbers are placed to the right of j while i <= j invariant 0 <= i <= j + 1 <= a.Length invariant multiset(a[..]) == old(multiset(a[..])) invariant forall k :: 0 <= k < i ==> odd(a[k]) invariant forall k :: j < k < a.Length ==> even(a[k]) { if even(a[i]) && odd(a[j]) { a[i], a[j] := a[j], a[i]; } if odd(a[i]) { i := i + 1; } if even(a[j]) { j := j - 1; } } } predicate odd(n: nat) { n % 2 == 1 } predicate even(n: nat) { n % 2 == 0 } method testPartitionOddEven() { var a: array<nat> := new [] [1, 2, 3]; assert a[..] == [1, 2, 3]; partitionOddEven(a); assert a[..] == [1, 3, 2] || a[..] == [3, 1, 2]; }
DafnyProjects_tmp_tmp2acw_s4s_partitionOddEven.dfy
128
128
Dafny program: 128
method sqrt(x: real) returns (r: real) requires x >= 0.0 ensures r * r == x && r >= 0.0 method testSqrt() { var r := sqrt(4.0); //if (2.0 < r) { monotonicSquare(2.0, r); } if (r < 2.0) { monotonicSquare(r, 2.0); } } lemma monotonicMult(c: real, x: real, y: real) requires x < y && c > 0.0 ensures c * x < c * y {} lemma monotonicSquare(x: real, y: real) requires 0.0 < x < y ensures 0.0 < x * x < y * y { monotonicMult(x, x, y); }
method sqrt(x: real) returns (r: real) requires x >= 0.0 ensures r * r == x && r >= 0.0 method testSqrt() { var r := sqrt(4.0); //if (2.0 < r) { monotonicSquare(2.0, r); } if (r < 2.0) { monotonicSquare(r, 2.0); } assert r == 2.0; } lemma monotonicMult(c: real, x: real, y: real) requires x < y && c > 0.0 ensures c * x < c * y {} lemma monotonicSquare(x: real, y: real) requires 0.0 < x < y ensures 0.0 < x * x < y * y { monotonicMult(x, x, y); }
DafnyProjects_tmp_tmp2acw_s4s_sqrt.dfy
129
129
Dafny program: 129
ghost function Count(hi: nat, s:seq<int>): int requires 0 <= hi <= |s| { if hi == 0 then 0 else if s[hi-1]%2 == 0 then 1 + Count(hi-1, s) else Count(hi-1, s) } method FooCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) modifies b ensures p == Count(CountIndex,a) { if CountIndex == 0{ p :=0; } else{ (a[CountIndex-1]%2 !=0 ==> |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a)); if a[CountIndex-1]%2==0{ var d := FooCount(CountIndex -1,a,b); p:= d+1; }else{ var d:= FooCount(CountIndex -1,a,b); p:= d; } b[CountIndex-1] := p; } } method FooPreCompute(a:array<int>,b:array<int>) requires a.Length == b.Length modifies b { var CountIndex := 1; while CountIndex != a.Length + 1 { var p := FooCount(CountIndex,a[..],b); CountIndex := CountIndex +1; } } method ComputeCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) modifies b ensures p == Count(CountIndex,a) { if CountIndex == 0{ p :=0; } else{ if a[CountIndex-1]%2==0{ var d := ComputeCount(CountIndex -1,a,b); p:= d+1; }else{ var d:= ComputeCount(CountIndex -1,a,b); p:= d; } b[CountIndex-1] := p; } } method PreCompute(a:array<int>,b:array<int>)returns(p:nat) requires a.Length == b.Length modifies b ensures (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) && forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) { && (forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) ); p := ComputeCount(b.Length,a[..],b); } method Evens(a:array<int>) returns (c:array2<int>) // modifies c // ensures invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 { c := new int[a.Length,a.Length]; var b := new int[a.Length]; var foo := PreCompute(a,b); var m := 0; while m != a.Length modifies c { var n := 0; while n != a.Length modifies c { if (n < m) { c[m,n] := 0; }else { if m > 0 { c[m,n] := b[n] - b[m-1]; }else{ c[m,n] := b[n]; } } n := n + 1; } m := m + 1; } } method Mult(x:int, y:int) returns (r:int) requires x>= 0 && y>=0 ensures r == x*y { if x==0 { r:=0; }else{ var z:= Mult(x-1,y); r:=z+y; } }
ghost function Count(hi: nat, s:seq<int>): int requires 0 <= hi <= |s| decreases hi { if hi == 0 then 0 else if s[hi-1]%2 == 0 then 1 + Count(hi-1, s) else Count(hi-1, s) } method FooCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) decreases CountIndex modifies b ensures p == Count(CountIndex,a) { assert CountIndex == 0 || (|a| == b.Length && 1<=CountIndex <= |a|); assert CountIndex == 0 || (|a| == b.Length && 0<=CountIndex -1 <= |a|); assert CountIndex!=0 ==> |a| == b.Length && 0<=CountIndex -1 <= |a|; assert CountIndex == 0 ==> true && CountIndex != 0 ==> |a| == b.Length && 0<=CountIndex -1 <= |a|; if CountIndex == 0{ assert true; assert 0 == 0; assert 0 == Count(0,a); p :=0; assert p == Count(CountIndex,a); } else{ assert |a| == b.Length && 0<=CountIndex-1 <=|a|; assert (a[CountIndex-1]%2 ==0 ==>|a| == b.Length && 0<= CountIndex -1 <|a| && 1+ Count(CountIndex-1,a) == Count(CountIndex,a)) && (a[CountIndex-1]%2 !=0 ==> |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a)); if a[CountIndex-1]%2==0{ assert |a| == b.Length && 0<= CountIndex -1 <|a| && 1+ Count(CountIndex-1,a) == Count(CountIndex,a); var d := FooCount(CountIndex -1,a,b); assert d+1 == Count(CountIndex,a); p:= d+1; assert p == Count(CountIndex,a); }else{ assert |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a); assert |a| == b.Length && 0<= CountIndex -1 <|a| && forall p'::p' ==Count(CountIndex-1,a) ==> p'==Count(CountIndex,a); var d:= FooCount(CountIndex -1,a,b); assert d == Count(CountIndex,a); p:= d; assert p == Count(CountIndex,a); } b[CountIndex-1] := p; assert p == Count(CountIndex,a); } } method FooPreCompute(a:array<int>,b:array<int>) requires a.Length == b.Length modifies b { var CountIndex := 1; while CountIndex != a.Length + 1 decreases a.Length + 1 - CountIndex invariant 1 <= CountIndex <= a.Length +1; { assert (CountIndex == 0 || (a.Length == b.Length && 1 <= CountIndex <= a.Length)) && forall a'::a' ==Count(CountIndex,a[..]) ==> a' ==Count(CountIndex,a[..]); var p := FooCount(CountIndex,a[..],b); assert 1<= CountIndex <= a.Length; assert 1 <= CountIndex + 1<= a.Length +1; CountIndex := CountIndex +1; assert 1 <= CountIndex <= a.Length +1; } } method ComputeCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) decreases CountIndex modifies b ensures p == Count(CountIndex,a) { if CountIndex == 0{ p :=0; } else{ if a[CountIndex-1]%2==0{ var d := ComputeCount(CountIndex -1,a,b); p:= d+1; }else{ var d:= ComputeCount(CountIndex -1,a,b); p:= d; } b[CountIndex-1] := p; } } method PreCompute(a:array<int>,b:array<int>)returns(p:nat) requires a.Length == b.Length modifies b ensures (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) && forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) { assert (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) && (forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) ); p := ComputeCount(b.Length,a[..],b); } method Evens(a:array<int>) returns (c:array2<int>) // modifies c // ensures invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 { c := new int[a.Length,a.Length]; var b := new int[a.Length]; var foo := PreCompute(a,b); var m := 0; while m != a.Length decreases a.Length - m modifies c invariant 0 <= m <= a.Length invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i>0 ==> c[i,j] == b[j] - b[i-1] invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i == 0 ==> c[i,j] == b[j] { var n := 0; while n != a.Length decreases a.Length - n modifies c invariant 0 <= n <= a.Length invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 invariant forall j:: 0 <= j <n ==> j < m ==> c[m,j] == 0 invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i>0 ==> c[i,j] == b[j] - b[i-1] invariant forall j:: 0 <= j <n ==> j>=m ==> m>0 ==> c[m,j] == b[j] - b[m-1] invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i == 0 ==> c[i,j] == b[j] invariant forall j:: 0 <= j <n ==> j>=m ==> m==0 ==> c[m,j] == b[j] { if (n < m) { c[m,n] := 0; }else { if m > 0 { c[m,n] := b[n] - b[m-1]; }else{ c[m,n] := b[n]; } } n := n + 1; } m := m + 1; } } method Mult(x:int, y:int) returns (r:int) requires x>= 0 && y>=0 decreases x ensures r == x*y { if x==0 { r:=0; }else{ assert x-1>= 0 && y>= 0&& (x-1)*y + y== x*y; var z:= Mult(x-1,y); assert z+y == x*y; r:=z+y; assert r == x*y; } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_A2_Q1_trimmed copy - 副本.dfy
131
131
Dafny program: 131
method LinearSeach0<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) { n := 0; while n != a.Length { if P(a[n]) {return;} n := n + 1; } } predicate P(n: int) { n % 2 == 0 } method TestLinearSearch() { /* var a := new int[3][44,2,56]; var n := LinearSeach0<int>(a,P); */ var a := new int[3][1,2,3]; var n := LinearSeach1<int>(a,P); } method LinearSeach1<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> !P(a[i]) { n := 0; while n != a.Length { if P(a[n]) {return;} n := n + 1; } }
method LinearSeach0<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) { n := 0; while n != a.Length invariant 0 <= n <= a.Length { if P(a[n]) {return;} n := n + 1; } } predicate P(n: int) { n % 2 == 0 } method TestLinearSearch() { /* var a := new int[3][44,2,56]; var n := LinearSeach0<int>(a,P); assert n == 1 || n == 2 || n == 3 || n == 0; */ var a := new int[3][1,2,3]; var n := LinearSeach1<int>(a,P); assert n == 1 || n == 2 || n==3 || n == 0; } method LinearSeach1<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> !P(a[i]) { n := 0; while n != a.Length invariant 0 <= n <= a.Length invariant forall i :: 0<=i<n ==> !P(a[i]) { if P(a[n]) {return;} n := n + 1; } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_Week4__LinearSearch.dfy
132
132
Dafny program: 132
method LinearSearch<T>(a: array<T>, P: T -> bool) returns (n: int) ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < a.Length ==> ! P(a[i]) { n := 0; while n != a.Length { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch1<T>(a: array<T>, P: T -> bool, s1:seq<T>) returns (n: int) requires |s1| <= a.Length requires forall i:: 0<= i <|s1| ==> s1[i] == a[i] ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < |s1| ==> ! P(a[i]) { n := 0; while n != |s1| { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch2<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; position := 0; while n != |s1| { if data[|s1|-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method LinearSearch3<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && |s1| != 0 // ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; var n1 := |s1|; position := 0; while n != |s1| { if data[data.Length -n1 +n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; }
method LinearSearch<T>(a: array<T>, P: T -> bool) returns (n: int) ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < a.Length ==> ! P(a[i]) { n := 0; while n != a.Length decreases a.Length - n invariant 0 <= n <= a.Length invariant forall i :: 0 <= i < n ==> ! P(a[i]) invariant n == -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch1<T>(a: array<T>, P: T -> bool, s1:seq<T>) returns (n: int) requires |s1| <= a.Length requires forall i:: 0<= i <|s1| ==> s1[i] == a[i] ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < |s1| ==> ! P(a[i]) { n := 0; while n != |s1| decreases |s1| - n invariant 0 <= n <= |s1| invariant forall i :: 0 <= i < n ==> ! P(a[i]) invariant n == -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch2<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; position := 0; while n != |s1| decreases |s1| - n invariant 0 <= n <= |s1| invariant position >= 1 ==> exists i::0 <=i < |s1| && data[i] == Element invariant forall i :: |s1|-1-n < i < |s1|==> data[i] != Element { if data[|s1|-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method LinearSearch3<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && |s1| != 0 // ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; var n1 := |s1|; position := 0; while n != |s1| decreases |s1| - n invariant 0 <= n <= |s1| invariant position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element invariant forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element invariant forall i :: |s1| - 1- n < i < |s1| -1 ==> s1[i] != Element { if data[data.Length -n1 +n] == Element { position := n + 1; assert data [data.Length-n1] == s1[|s1| -1]; assert data[data.Length -n1 +n] == s1[n1-1-n]; assert forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i]; assert forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element; assert forall i :: |s1| - 1 > i > |s1| -1 -n ==> s1[i] != Element; assert forall i:: data.Length - |s1| < i< data.Length-1 ==> data[i] == s1[data.Length-i-1]; return position; } n := n + 1; } position := -1; assert |s1| <= data.Length; assert |s1| != 0 ==> s1[0] == data[data.Length-1]; assert |s1| != 0 ==> data[data.Length-n1] == s1[|s1| -1]; assert forall i:: data.Length - |s1| < i< data.Length-1 ==> data[i] == s1[data.Length-i-1]; assert forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element; assert forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i]; assert forall i :: |s1| - 1 > i > |s1| -1 -n ==> s1[i] != Element; }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week4_tute_ex4.dfy
133
133
Dafny program: 133
function Power(n:nat):nat { if n == 0 then 1 else 2 * Power(n-1) } method CalcPower(n:nat) returns (p:nat) ensures p == 2*n; { p := 2*n; } method ComputePower(n:nat) returns (p:nat) ensures p == Power(n) { p:=1; var i:=0; while i!=n { p:= CalcPower(p); i:=i+1; } }
function Power(n:nat):nat { if n == 0 then 1 else 2 * Power(n-1) } method CalcPower(n:nat) returns (p:nat) ensures p == 2*n; { p := 2*n; } method ComputePower(n:nat) returns (p:nat) ensures p == Power(n) { p:=1; var i:=0; while i!=n invariant 0 <= i <= n invariant p *Power(n-i) == Power(n) { p:= CalcPower(p); i:=i+1; } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week5_ComputePower.dfy
134
134
Dafny program: 134
class TwoStacks<T(0)(==)> { //abstract state ghost var s1 :seq<T> ghost var s2 :seq<T> ghost const N :nat // maximum size of the stacks ghost var Repr : set<object> //concrete state var data: array<T> var n1: nat // number of elements in the stack 1 var n2: nat // number of elements in the stack 2 ghost predicate Valid() reads this,Repr ensures Valid() ==> this in Repr && |s1| + |s2| <= N && 0 <= |s1| <= N && 0 <=|s2| <= N { this in Repr && data in Repr && data.Length == N && 0 <= |s1| + |s2| <= N && 0 <=|s1| <= N && 0 <=|s2| <= N && (|s1| != 0 ==> forall i:: 0<= i < |s1| ==> s1[i] == data[i]) && (|s2| != 0 ==> forall i:: 0<= i < |s2| ==> s2[i] == data[data.Length-1-i]) && n1 == |s1| && n2 == |s2| } constructor (N: nat) ensures Valid() && fresh(Repr) ensures s1 == s2 == [] && this.N == N { s1,s2,this.N := [],[],N; data := new T[N]; n1, n2 := 0, 0; Repr := {this, data}; } method push1(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s1|) != N && old(|s1|) + old(|s2|) != N ==> s1 == old(s1) + [element]; ensures old(|s1|) == N ==> FullStatus == false ensures old(|s1|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == data.Length { FullStatus := false; }else { if n1 != data.Length && n1 + n2 != data.Length{ s1 := old(s1) + [element] ; data[n1] := element; n1 := n1 +1; FullStatus := true; }else{ FullStatus := false; } } } method push2(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s2|) != N && old(|s1|) + old(|s2|) != N ==> s2 == old(s2) + [element]; ensures old(|s2|) == N ==> FullStatus == false ensures old(|s2|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == data.Length { FullStatus := false; }else { if n2 != data.Length && n1 + n2 != data.Length{ s2 := old(s2) + [element] ; data[data.Length-1-n2] := element; n2 := n2 +1; FullStatus := true; }else{ FullStatus := false; } } } method pop1() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s1|) != 0 ==> s1 == old(s1[0..|s1|-1]) && EmptyStatus == true && PopedItem == old(s1[|s1|-1]) ensures old(|s1|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == 0 { EmptyStatus := false; PopedItem := *; } else{ s1 := old(s1[0..|s1|-1]); PopedItem := data[n1-1]; n1 := n1 -1; EmptyStatus := true; } } method pop2() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s2|) != 0 ==> s2 == old(s2[0..|s2|-1]) && EmptyStatus == true && PopedItem == old(s2[|s2|-1]) ensures old(|s2|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == 0 { EmptyStatus := false; PopedItem := *; } else{ s2 := old(s2[0..|s2|-1]); PopedItem := data[data.Length-n2]; n2 := n2 -1; EmptyStatus := true; } } method peek1() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty1() ==> EmptyStatus == false ensures !Empty1() ==> EmptyStatus == true && TopItem == s1[|s1|-1] ensures Valid() { if n1 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[n1-1]; EmptyStatus := true; } } method peek2() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty2() ==> EmptyStatus == false ensures !Empty2() ==> EmptyStatus == true && TopItem == s2[|s2|-1] ensures Valid() { if n2 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[data.Length-n2]; EmptyStatus := true; } } ghost predicate Empty1() requires Valid() reads this,Repr ensures Empty1() ==> |s1| == 0 ensures Valid() { |s1| == 0 && n1 == 0 } ghost predicate Empty2() reads this ensures Empty2() ==> |s2| == 0 { |s2| == 0 && n2 == 0 } method search1(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && !Empty1() ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element || Empty1() ensures Valid() { var n := 0; position := 0; while n != n1 { if data[n1-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method search3(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s2| && s2[i] == Element && !Empty2() // ensures position == -1 ==> forall i :: 0 <= i < |s2| ==> s2[i] != Element || Empty2() ensures Valid() { position := 0; var n := 0; while n != n2 { if data[data.Length - n2 + n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } }
class TwoStacks<T(0)(==)> { //abstract state ghost var s1 :seq<T> ghost var s2 :seq<T> ghost const N :nat // maximum size of the stacks ghost var Repr : set<object> //concrete state var data: array<T> var n1: nat // number of elements in the stack 1 var n2: nat // number of elements in the stack 2 ghost predicate Valid() reads this,Repr ensures Valid() ==> this in Repr && |s1| + |s2| <= N && 0 <= |s1| <= N && 0 <=|s2| <= N { this in Repr && data in Repr && data.Length == N && 0 <= |s1| + |s2| <= N && 0 <=|s1| <= N && 0 <=|s2| <= N && (|s1| != 0 ==> forall i:: 0<= i < |s1| ==> s1[i] == data[i]) && (|s2| != 0 ==> forall i:: 0<= i < |s2| ==> s2[i] == data[data.Length-1-i]) && n1 == |s1| && n2 == |s2| } constructor (N: nat) ensures Valid() && fresh(Repr) ensures s1 == s2 == [] && this.N == N { s1,s2,this.N := [],[],N; data := new T[N]; n1, n2 := 0, 0; Repr := {this, data}; } method push1(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s1|) != N && old(|s1|) + old(|s2|) != N ==> s1 == old(s1) + [element]; ensures old(|s1|) == N ==> FullStatus == false ensures old(|s1|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == data.Length { FullStatus := false; }else { if n1 != data.Length && n1 + n2 != data.Length{ s1 := old(s1) + [element] ; data[n1] := element; n1 := n1 +1; FullStatus := true; }else{ FullStatus := false; } } } method push2(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s2|) != N && old(|s1|) + old(|s2|) != N ==> s2 == old(s2) + [element]; ensures old(|s2|) == N ==> FullStatus == false ensures old(|s2|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == data.Length { FullStatus := false; }else { if n2 != data.Length && n1 + n2 != data.Length{ s2 := old(s2) + [element] ; data[data.Length-1-n2] := element; n2 := n2 +1; FullStatus := true; }else{ FullStatus := false; } } } method pop1() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s1|) != 0 ==> s1 == old(s1[0..|s1|-1]) && EmptyStatus == true && PopedItem == old(s1[|s1|-1]) ensures old(|s1|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == 0 { EmptyStatus := false; PopedItem := *; } else{ s1 := old(s1[0..|s1|-1]); PopedItem := data[n1-1]; n1 := n1 -1; EmptyStatus := true; } } method pop2() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s2|) != 0 ==> s2 == old(s2[0..|s2|-1]) && EmptyStatus == true && PopedItem == old(s2[|s2|-1]) ensures old(|s2|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == 0 { EmptyStatus := false; PopedItem := *; } else{ s2 := old(s2[0..|s2|-1]); PopedItem := data[data.Length-n2]; n2 := n2 -1; EmptyStatus := true; } } method peek1() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty1() ==> EmptyStatus == false ensures !Empty1() ==> EmptyStatus == true && TopItem == s1[|s1|-1] ensures Valid() { if n1 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[n1-1]; EmptyStatus := true; } } method peek2() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty2() ==> EmptyStatus == false ensures !Empty2() ==> EmptyStatus == true && TopItem == s2[|s2|-1] ensures Valid() { if n2 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[data.Length-n2]; EmptyStatus := true; } } ghost predicate Empty1() requires Valid() reads this,Repr ensures Empty1() ==> |s1| == 0 ensures Valid() { |s1| == 0 && n1 == 0 } ghost predicate Empty2() reads this ensures Empty2() ==> |s2| == 0 { |s2| == 0 && n2 == 0 } method search1(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && !Empty1() ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element || Empty1() ensures Valid() { var n := 0; position := 0; while n != n1 decreases |s1| - n invariant Valid() invariant 0 <= n <= |s1| invariant position >= 1 ==> exists i::0 <= i < |s1| && s1[i] == Element invariant forall i :: |s1|-1-n < i < |s1|==> s1[i] != Element { if data[n1-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method search3(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s2| && s2[i] == Element && !Empty2() // ensures position == -1 ==> forall i :: 0 <= i < |s2| ==> s2[i] != Element || Empty2() ensures Valid() { position := 0; var n := 0; while n != n2 decreases |s2| - n invariant 0 <= n <= |s2| invariant Valid() invariant position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element invariant forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element invariant forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element { if data[data.Length - n2 + n] == Element { position := n + 1; assert data[data.Length -n2 +n] == s2[n2-1-n]; assert position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element; assert forall i:: data.Length - |s2| < i< data.Length-1 ==> data[i] == s2[data.Length-i-1]; assert forall i:: 0 <= i < |s2| ==> s2[i] == data[data.Length-i-1]; assert forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element; assert forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element; return position; } n := n + 1; } position := -1; assert position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element; assert forall i:: data.Length - |s2| < i< data.Length-1 ==> data[i] == s2[data.Length-i-1]; assert forall i:: 0 <= i < |s2| ==> s2[i] == data[data.Length-i-1]; assert forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element; assert forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element; } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_a3 copy 2.dfy