test_ID
stringlengths
3
3
test_file
stringlengths
14
119
ground_truth
stringlengths
70
28.7k
hints_removed
stringlengths
58
28.7k
000
630-dafny_tmp_tmpz2kokaiq_Solution.dfy
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; }
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; }
001
703FinalProject_tmp_tmpr_10rn4z_DP-GD.dfy
method DPGD_GradientPerturbation (size:int, learning_rate:real, noise_scale:real, gradient_norm_bound:real, iterations:int) returns (Para:real, PrivacyLost:real) requires iterations>=0 requires size>=0 requires noise_scale >= 1.0 requires -1.0 <= gradient_norm_bound <= 1.0 { var thetha:array<real> := new real[iterations+1]; thetha[0] := *; var alpha:real := 0.0; var tau:real := *; assume(tau>=0.0); var t :int := 0; var constant:real := (size as real) * tau; while (t < iterations) invariant t <= iterations invariant alpha == t as real * constant { var i :int := 0; var beta:real := 0.0; var summation_gradient:real := 0.0; while (i< size) invariant i <= size invariant beta == i as real * tau { var gradient:real := *; // Note: We do not need to clip the value of the gradient. // Instead, we clip the sensitivity of the gradient by the gradient_norm_bound provided by the user var eta:real := *; beta := beta + tau; var eta_hat:real := - gradient_norm_bound; assert (gradient_norm_bound + eta_hat == 0.0); summation_gradient := summation_gradient + gradient + eta; i := i + 1; } alpha := alpha + beta; thetha[t+1] := thetha[t] - learning_rate*summation_gradient; t := t+1; } assert(t==iterations); assert(alpha == iterations as real * constant); Para := thetha[iterations]; PrivacyLost := alpha; }
method DPGD_GradientPerturbation (size:int, learning_rate:real, noise_scale:real, gradient_norm_bound:real, iterations:int) returns (Para:real, PrivacyLost:real) requires iterations>=0 requires size>=0 requires noise_scale >= 1.0 requires -1.0 <= gradient_norm_bound <= 1.0 { var thetha:array<real> := new real[iterations+1]; thetha[0] := *; var alpha:real := 0.0; var tau:real := *; assume(tau>=0.0); var t :int := 0; var constant:real := (size as real) * tau; while (t < iterations) { var i :int := 0; var beta:real := 0.0; var summation_gradient:real := 0.0; while (i< size) { var gradient:real := *; // Note: We do not need to clip the value of the gradient. // Instead, we clip the sensitivity of the gradient by the gradient_norm_bound provided by the user var eta:real := *; beta := beta + tau; var eta_hat:real := - gradient_norm_bound; summation_gradient := summation_gradient + gradient + eta; i := i + 1; } alpha := alpha + beta; thetha[t+1] := thetha[t] - learning_rate*summation_gradient; t := t+1; } Para := thetha[iterations]; PrivacyLost := alpha; }
002
703FinalProject_tmp_tmpr_10rn4z_gaussian.dfy
// VERIFY USING DAFNY: // /Applications/dafny/dafny /Users/apple/GaussianDP/Dafny/gaussian.dfy method gaussian (size:int, q: array<real>, q_hat: array<real>) returns (out: array<real>) requires q_hat.Length==size requires q.Length==size requires size > 0 requires arraySquaredSum(q_hat[..]) <= 1.0 { var i : int := 0; var alpha : real := arraySquaredSum(q_hat[..1]); var eta: real := 0.0; var eta_hat: real := 0.0; out := new real[size]; while (i <size) invariant 0 < i <= size ==> alpha <= arraySquaredSum(q_hat[..i]) invariant i<=size { eta := *; eta_hat := - q_hat[i]; alpha := arraySquaredSum(q_hat[..i+1]); assert (q_hat[i] + eta_hat ==0.0); out[i] := q[i] + eta; i := i+1; } assert i==size; assert alpha <= arraySquaredSum(q_hat[..size]); assert q_hat[..size] == q_hat[..]; assert alpha <= arraySquaredSum(q_hat[..]); assert alpha <= 1.0; } function arraySquaredSum(a: seq<real>): real requires |a| > 0 { if |a| == 1 then a[0]*a[0] else (a[0]*a[0]) + arraySquaredSum(a[1..]) }
// VERIFY USING DAFNY: // /Applications/dafny/dafny /Users/apple/GaussianDP/Dafny/gaussian.dfy method gaussian (size:int, q: array<real>, q_hat: array<real>) returns (out: array<real>) requires q_hat.Length==size requires q.Length==size requires size > 0 requires arraySquaredSum(q_hat[..]) <= 1.0 { var i : int := 0; var alpha : real := arraySquaredSum(q_hat[..1]); var eta: real := 0.0; var eta_hat: real := 0.0; out := new real[size]; while (i <size) { eta := *; eta_hat := - q_hat[i]; alpha := arraySquaredSum(q_hat[..i+1]); out[i] := q[i] + eta; i := i+1; } } function arraySquaredSum(a: seq<real>): real requires |a| > 0 { if |a| == 1 then a[0]*a[0] else (a[0]*a[0]) + arraySquaredSum(a[1..]) }
003
AssertivePrograming_tmp_tmpwf43uz0e_DivMode_Unary.dfy
// 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; }
// 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; }
004
AssertivePrograming_tmp_tmpwf43uz0e_Find_Substring.dfy
// 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])); }
// 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]; }
005
AssertivePrograming_tmp_tmpwf43uz0e_MergeSort.dfy
// 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]; }
// 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]; }
006
BPTree-verif_tmp_tmpq1z6xm1d_Utils.dfy
// 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; }
// 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; } }
007
BinarySearchTree_tmp_tmp_bn2twp5_bst4copy.dfy
datatype Tree = Empty | Node(left: Tree, value: int, right: Tree) predicate BinarySearchTree(tree: Tree) decreases tree { match tree case Empty => true case Node(_,_,_) => (tree.left == Empty || tree.left.value < tree.value) && (tree.right == Empty || tree.right.value > tree.value) && BinarySearchTree(tree.left) && BinarySearchTree(tree.right) && minValue(tree.right, tree.value) && maxValue(tree.left, tree.value) } predicate maxValue(tree: Tree, max: int) decreases tree { match tree case Empty => true case Node(left,v,right) => (max > v) && maxValue(left, max) && maxValue(right, max) } predicate minValue(tree: Tree, min: int) decreases tree { match tree case Empty => true case Node(left,v,right) => (min < v) && minValue(left, min) && minValue(right, min) } method GetMin(tree: Tree) returns (res: int) { match tree { case Empty => res := 0; case Node (Empty, value, Empty) => res := tree.value; case Node (Empty, value, right) => res := tree.value; case Node (left, value, right) => var minval := tree.value; minval := GetMin(tree.left); var tmp := Node(tree.left, minval, tree.right); res := tmp.value; } } method GetMax(tree: Tree) returns (res: int){ match tree { case Empty => res := 0; case Node (Empty, value, Empty) => res := tree.value; case Node (left, value, Empty) => res := tree.value; case Node (left, value, right) => var minval := tree.value; minval := GetMax(tree.right); var tmp := Node(tree.left, minval, tree.right); res := tmp.value; } } method insert(tree: Tree, value : int) returns (res: Tree) requires BinarySearchTree(tree) decreases tree; ensures BinarySearchTree(res) { res := insertRecursion(tree, value); } method insertRecursion(tree: Tree, value: int) returns (res: Tree) requires BinarySearchTree(tree) decreases tree; ensures res != Empty ==> BinarySearchTree(res) ensures forall x :: minValue(tree, x) && x < value ==> minValue(res, x) ensures forall x :: maxValue(tree, x) && x > value ==> maxValue(res, x) { match tree { case Empty => res := Node(Empty, value, Empty); case Node(_,_,_) => var temp: Tree; if(value == tree.value) { return tree; } if(value < tree.value){ temp := insertRecursion(tree.left, value); res := Node(temp, tree.value, tree.right); }else if (value > tree.value){ temp := insertRecursion(tree.right, value); res := Node(tree.left, tree.value, temp); } } } method delete(tree: Tree, value: int) returns (res: Tree) requires BinarySearchTree(tree) decreases tree; //ensures BinarySearchTree(res) //ensures res != Empty ==> BinarySearchTree(res) { match tree { case Empty => return tree; case Node(_,_ ,_) => var temp: Tree; if (value < tree.value){ temp := delete(tree.left, value); res := Node(temp, tree.value, tree.right); } else if (value > tree.value){ temp := delete(tree.right, value); res := Node(tree.left, tree.value, temp); } else { if (tree.left == Empty){ return tree.right; } else if (tree.right == Empty) { return tree.left; } var minVal := GetMin(tree.right); temp := delete(tree.right, minVal); res := Node(tree.left, minVal, temp); //assert BinarySearchTree(res); } } } method Inorder(tree: Tree) { match tree { case Empty => case Node(left, value, right) => Inorder(tree.left); print tree.value, ", "; Inorder(tree.right); } } method Postorder(tree: Tree) { match tree { case Empty => case Node(left, value, right) => Postorder(tree.left); Postorder(tree.right); print tree.value, ", "; } } method Main() { var tree := insert(Empty, 3); var u := insert(tree, 2); u := insert(u, 7); u := insert(u, 6); u := insert(u, 9); print "This is Inorder: "; Inorder(u); print "\n"; //u := delete (u, 1); print "This is Postorder: "; Postorder(u); print "\n"; print "tree before delete: ", u, "\n"; u := delete(u, 7); print "tree after delete: ", u, "\n"; print "This is Inorder: "; Inorder(u); print "\n"; print "This is Postorder: "; Postorder(u); // var res := GetMin(u); // var max := GetMax(u); // print "this is max: ", max; //print "this is res: ", res; //print u; }
datatype Tree = Empty | Node(left: Tree, value: int, right: Tree) predicate BinarySearchTree(tree: Tree) { match tree case Empty => true case Node(_,_,_) => (tree.left == Empty || tree.left.value < tree.value) && (tree.right == Empty || tree.right.value > tree.value) && BinarySearchTree(tree.left) && BinarySearchTree(tree.right) && minValue(tree.right, tree.value) && maxValue(tree.left, tree.value) } predicate maxValue(tree: Tree, max: int) { match tree case Empty => true case Node(left,v,right) => (max > v) && maxValue(left, max) && maxValue(right, max) } predicate minValue(tree: Tree, min: int) { match tree case Empty => true case Node(left,v,right) => (min < v) && minValue(left, min) && minValue(right, min) } method GetMin(tree: Tree) returns (res: int) { match tree { case Empty => res := 0; case Node (Empty, value, Empty) => res := tree.value; case Node (Empty, value, right) => res := tree.value; case Node (left, value, right) => var minval := tree.value; minval := GetMin(tree.left); var tmp := Node(tree.left, minval, tree.right); res := tmp.value; } } method GetMax(tree: Tree) returns (res: int){ match tree { case Empty => res := 0; case Node (Empty, value, Empty) => res := tree.value; case Node (left, value, Empty) => res := tree.value; case Node (left, value, right) => var minval := tree.value; minval := GetMax(tree.right); var tmp := Node(tree.left, minval, tree.right); res := tmp.value; } } method insert(tree: Tree, value : int) returns (res: Tree) requires BinarySearchTree(tree) ensures BinarySearchTree(res) { res := insertRecursion(tree, value); } method insertRecursion(tree: Tree, value: int) returns (res: Tree) requires BinarySearchTree(tree) ensures res != Empty ==> BinarySearchTree(res) ensures forall x :: minValue(tree, x) && x < value ==> minValue(res, x) ensures forall x :: maxValue(tree, x) && x > value ==> maxValue(res, x) { match tree { case Empty => res := Node(Empty, value, Empty); case Node(_,_,_) => var temp: Tree; if(value == tree.value) { return tree; } if(value < tree.value){ temp := insertRecursion(tree.left, value); res := Node(temp, tree.value, tree.right); }else if (value > tree.value){ temp := insertRecursion(tree.right, value); res := Node(tree.left, tree.value, temp); } } } method delete(tree: Tree, value: int) returns (res: Tree) requires BinarySearchTree(tree) //ensures BinarySearchTree(res) //ensures res != Empty ==> BinarySearchTree(res) { match tree { case Empty => return tree; case Node(_,_ ,_) => var temp: Tree; if (value < tree.value){ temp := delete(tree.left, value); res := Node(temp, tree.value, tree.right); } else if (value > tree.value){ temp := delete(tree.right, value); res := Node(tree.left, tree.value, temp); } else { if (tree.left == Empty){ return tree.right; } else if (tree.right == Empty) { return tree.left; } var minVal := GetMin(tree.right); temp := delete(tree.right, minVal); res := Node(tree.left, minVal, temp); //assert BinarySearchTree(res); } } } method Inorder(tree: Tree) { match tree { case Empty => case Node(left, value, right) => Inorder(tree.left); print tree.value, ", "; Inorder(tree.right); } } method Postorder(tree: Tree) { match tree { case Empty => case Node(left, value, right) => Postorder(tree.left); Postorder(tree.right); print tree.value, ", "; } } method Main() { var tree := insert(Empty, 3); var u := insert(tree, 2); u := insert(u, 7); u := insert(u, 6); u := insert(u, 9); print "This is Inorder: "; Inorder(u); print "\n"; //u := delete (u, 1); print "This is Postorder: "; Postorder(u); print "\n"; print "tree before delete: ", u, "\n"; u := delete(u, 7); print "tree after delete: ", u, "\n"; print "This is Inorder: "; Inorder(u); print "\n"; print "This is Postorder: "; Postorder(u); // var res := GetMin(u); // var max := GetMax(u); // print "this is max: ", max; //print "this is res: ", res; //print u; }
008
CO3408-Advanced-Software-Modelling-Assignment-2022-23-Part-2-A-Specification-Spectacular_tmp_tmp4pj4p2zx_car_park.dfy
class {:autocontracts} CarPark { const totalSpaces: nat := 10; const normalSpaces: nat:= 7; const reservedSpaces: nat := 3; const badParkingBuffer: int := 5; var weekend: bool; var subscriptions: set<string>; var carPark: set<string>; var reservedCarPark: set<string>; constructor() requires true ensures this.subscriptions == {} && this.carPark == {} && this.reservedCarPark == {} && this.weekend == false; { this.subscriptions := {}; this.carPark := {}; this.reservedCarPark := {}; this.weekend := false; } // This predicate checks if the car park is in a valid state at all times. // It checks if the sets of cars in the car park and the reserved car park are disjoint and share no values, // the total number of cars in the car park is less than or equal to the total number of spaces in // the car park plus the bad parking buffer, the number of normal spaces plus reserved spaces is // equal to the total number of spaces, and the number of cars in the reserved car park is less than or equal // to the number of reserved spaces ghost predicate Valid() reads this { carPark * reservedCarPark == {} && |carPark| <= totalSpaces + badParkingBuffer && (normalSpaces + reservedSpaces) == totalSpaces && |reservedCarPark| <= reservedSpaces } // The method maintains the invariant that if success is true, then the car parameter is removed from either // the carPark or the reservedCarPark set. Otherwise, neither set is modified method leaveCarPark(car: string) returns (success: bool) requires true modifies this ensures success ==> (((car in old(carPark)) && carPark == old(carPark) - {car} && reservedCarPark == old(reservedCarPark)) || ((car in old(reservedCarPark)) && reservedCarPark == old(reservedCarPark) - {car} && carPark == old(carPark))); ensures success ==> (car !in carPark) && (car !in reservedCarPark); ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && (car !in old(carPark)) && (car !in old(reservedCarPark)); ensures subscriptions == old(subscriptions) && weekend == old(weekend); { success := false; if car in carPark { carPark := carPark - {car}; success := true; } else if car in reservedCarPark { reservedCarPark := reservedCarPark - {car}; success := true; } } // The method maintains the invariant that the number of available spaces availableSpaces is updated correctly // based on the current state of the car park and whether it is a weekend or not method checkAvailability() returns (availableSpaces: int) requires true modifies this ensures weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) + (reservedSpaces - old(|reservedCarPark|)) - badParkingBuffer; ensures !weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) - badParkingBuffer; ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend) && subscriptions == old(subscriptions); { if (weekend){ availableSpaces := (normalSpaces - |carPark|) + (reservedSpaces - |reservedCarPark|) - badParkingBuffer; } else{ availableSpaces := (normalSpaces - |carPark|) - badParkingBuffer; } } // The method maintains the invariant that if success is true, then the car parameter is added to the // subscriptions set. Otherwise, the subscriptions set is not modified method makeSubscription(car: string) returns (success: bool) requires true modifies this ensures success ==> old(|subscriptions|) < reservedSpaces && car !in old(subscriptions) && subscriptions == old(subscriptions) + {car}; ensures !success ==> subscriptions == old(subscriptions) && (car in old(subscriptions) || old(|subscriptions|) >= reservedSpaces); ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend); { if |subscriptions| >= reservedSpaces || car in subscriptions { success := false; } else { subscriptions := subscriptions + {car}; success := true; } } // The method maintains the invariant that the weekend variable is set to true method openReservedArea() requires true modifies this ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == true && subscriptions == old(subscriptions); { weekend := true; } // The method maintains the invariant that the carPark, reservedCarPark, and subscriptions sets are all cleared method closeCarPark() requires true modifies this ensures carPark == {} && reservedCarPark == {} && subscriptions == {} ensures weekend == old(weekend); { carPark := {}; reservedCarPark := {}; subscriptions := {}; } // The method maintains the invariant that if success is true, then the car parameter is added to the carPark // set and the number of cars in the carPark set is less than the number of normal spaces minus the bad parking // buffer. Otherwise, the carPark and reservedCarPark sets are not modified method enterCarPark(car: string) returns (success: bool) requires true modifies this; ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|carPark|) < normalSpaces - badParkingBuffer); ensures success ==> carPark == old(carPark) + {car}; ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark); ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|carPark|) >= normalSpaces - badParkingBuffer)); ensures subscriptions == old(subscriptions) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend); { if (|carPark| >= normalSpaces - badParkingBuffer || car in carPark || car in reservedCarPark) { return false; } else { carPark := carPark + {car}; return true; } } // The method maintains the invariant that if success is true, then the car parameter is added to the // reservedCarPark set and the number of cars in the reservedCarPark set is less than the number of // reserved spaces and either the weekend variable is true or the car parameter is in the subscriptions set. // Otherwise, the carPark and reservedCarPark sets are not modified method enterReservedCarPark(car: string) returns (success: bool) requires true modifies this; ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|reservedCarPark|) < reservedSpaces) && (car in subscriptions || weekend == true); ensures success ==> reservedCarPark == old(reservedCarPark) + {car}; ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark); ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|reservedCarPark|) >= reservedSpaces) || (car !in subscriptions && weekend == false)); ensures subscriptions == old(subscriptions) && carPark == old(carPark) && weekend == old(weekend); ensures weekend == old(weekend) && subscriptions == old(subscriptions); { if (|reservedCarPark| >= reservedSpaces || car in carPark || car in reservedCarPark || (car !in subscriptions && weekend == false)) { return false; } else { reservedCarPark := reservedCarPark + {car}; return true; } } } method Main() { // Initialises car park with 10 spaces, 3 of which are reserved and therefore 7 are normal var carPark := new CarPark(); // As we are allowing 5 spaces for idiots who can't park within the lines 7 - 5 == 2 var availableSpaces := carPark.checkAvailability(); assert availableSpaces == 2; // Test entering the car park with one car, One space should now be left var success := carPark.enterCarPark("car1"); availableSpaces := carPark.checkAvailability(); assert success && carPark.carPark == {"car1"} && availableSpaces == 1; // Test entering the car with another car, No spaces should be left success := carPark.enterCarPark("car2"); availableSpaces := carPark.checkAvailability(); assert success && "car2" in carPark.carPark && carPark.carPark == {"car1", "car2"} && availableSpaces == 0; // Test entering with another car, should return invalid as carpark is full // normalSpaces = 7, minus 5 spaces because of the bad parking buffer, therefore 2 spaces max success := carPark.enterCarPark("car3"); assert !success && carPark.carPark == {"car1", "car2"} && carPark.reservedCarPark == {}; // Test creating car subscription success := carPark.makeSubscription("car4"); assert success && carPark.subscriptions == {"car4"}; // Test entering the reserved carPark with a valid and an invalid option success := carPark.enterReservedCarPark("car4"); assert success && carPark.reservedCarPark == {"car4"}; // This car doesn't have a subscription so it should not be successful success := carPark.enterReservedCarPark("car5"); assert !success && carPark.reservedCarPark == {"car4"}; // Test filling the car subscription list success := carPark.makeSubscription("car6"); assert success && carPark.subscriptions == {"car4", "car6"}; success := carPark.makeSubscription("car7"); assert success && carPark.subscriptions == {"car4", "car6", "car7"}; // This won't add as reserved spaces are 3 and we can't have more subscriptions than reserved spaces success := carPark.makeSubscription("car8"); assert !success && carPark.subscriptions == {"car4", "car6", "car7"}; // Test filling reserved car park success := carPark.enterReservedCarPark("car6"); assert success && carPark.reservedCarPark == {"car4", "car6"}; success := carPark.enterReservedCarPark("car7"); assert success && carPark.reservedCarPark == {"car4", "car6", "car7"}; // Test leaving car park assert carPark.carPark == {"car1", "car2"}; success := carPark.leaveCarPark("car1"); assert success && carPark.carPark == {"car2"} && carPark.reservedCarPark == {"car4", "car6", "car7"}; // Test leaving with car that doesn't exist assert "car9" !in carPark.carPark && "car9" !in carPark.reservedCarPark; success := carPark.leaveCarPark("car9"); assert !success && carPark.carPark == {"car2"} && carPark.reservedCarPark == {"car4", "car6", "car7"}; // Test leaving reserved car park success := carPark.leaveCarPark("car6"); assert success && carPark.carPark == {"car2"} && carPark.reservedCarPark == {"car4", "car7"}; // Testing closing car park, all cars should be destroyed carPark.closeCarPark(); assert carPark.carPark == {} && carPark.reservedCarPark == {} && carPark.subscriptions == {}; } // Added due to timeout in Main method MainB () { var carPark := new CarPark(); // Test opening the reserved carPark assert carPark.weekend == false; carPark.openReservedArea(); assert carPark.weekend == true; // Test joining carPark on weekend with car without subscription var success := carPark.enterReservedCarPark("car3"); assert "car3" !in carPark.subscriptions && success && carPark.carPark == {} && carPark.reservedCarPark == {"car3"}; // Testing closing car park, all cars should be destroyed carPark.closeCarPark(); assert carPark.carPark == {} && carPark.reservedCarPark == {} && carPark.subscriptions == {}; }
class {:autocontracts} CarPark { const totalSpaces: nat := 10; const normalSpaces: nat:= 7; const reservedSpaces: nat := 3; const badParkingBuffer: int := 5; var weekend: bool; var subscriptions: set<string>; var carPark: set<string>; var reservedCarPark: set<string>; constructor() requires true ensures this.subscriptions == {} && this.carPark == {} && this.reservedCarPark == {} && this.weekend == false; { this.subscriptions := {}; this.carPark := {}; this.reservedCarPark := {}; this.weekend := false; } // This predicate checks if the car park is in a valid state at all times. // It checks if the sets of cars in the car park and the reserved car park are disjoint and share no values, // the total number of cars in the car park is less than or equal to the total number of spaces in // the car park plus the bad parking buffer, the number of normal spaces plus reserved spaces is // equal to the total number of spaces, and the number of cars in the reserved car park is less than or equal // to the number of reserved spaces ghost predicate Valid() reads this { carPark * reservedCarPark == {} && |carPark| <= totalSpaces + badParkingBuffer && (normalSpaces + reservedSpaces) == totalSpaces && |reservedCarPark| <= reservedSpaces } // The method maintains the invariant that if success is true, then the car parameter is removed from either // the carPark or the reservedCarPark set. Otherwise, neither set is modified method leaveCarPark(car: string) returns (success: bool) requires true modifies this ensures success ==> (((car in old(carPark)) && carPark == old(carPark) - {car} && reservedCarPark == old(reservedCarPark)) || ((car in old(reservedCarPark)) && reservedCarPark == old(reservedCarPark) - {car} && carPark == old(carPark))); ensures success ==> (car !in carPark) && (car !in reservedCarPark); ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && (car !in old(carPark)) && (car !in old(reservedCarPark)); ensures subscriptions == old(subscriptions) && weekend == old(weekend); { success := false; if car in carPark { carPark := carPark - {car}; success := true; } else if car in reservedCarPark { reservedCarPark := reservedCarPark - {car}; success := true; } } // The method maintains the invariant that the number of available spaces availableSpaces is updated correctly // based on the current state of the car park and whether it is a weekend or not method checkAvailability() returns (availableSpaces: int) requires true modifies this ensures weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) + (reservedSpaces - old(|reservedCarPark|)) - badParkingBuffer; ensures !weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) - badParkingBuffer; ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend) && subscriptions == old(subscriptions); { if (weekend){ availableSpaces := (normalSpaces - |carPark|) + (reservedSpaces - |reservedCarPark|) - badParkingBuffer; } else{ availableSpaces := (normalSpaces - |carPark|) - badParkingBuffer; } } // The method maintains the invariant that if success is true, then the car parameter is added to the // subscriptions set. Otherwise, the subscriptions set is not modified method makeSubscription(car: string) returns (success: bool) requires true modifies this ensures success ==> old(|subscriptions|) < reservedSpaces && car !in old(subscriptions) && subscriptions == old(subscriptions) + {car}; ensures !success ==> subscriptions == old(subscriptions) && (car in old(subscriptions) || old(|subscriptions|) >= reservedSpaces); ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend); { if |subscriptions| >= reservedSpaces || car in subscriptions { success := false; } else { subscriptions := subscriptions + {car}; success := true; } } // The method maintains the invariant that the weekend variable is set to true method openReservedArea() requires true modifies this ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == true && subscriptions == old(subscriptions); { weekend := true; } // The method maintains the invariant that the carPark, reservedCarPark, and subscriptions sets are all cleared method closeCarPark() requires true modifies this ensures carPark == {} && reservedCarPark == {} && subscriptions == {} ensures weekend == old(weekend); { carPark := {}; reservedCarPark := {}; subscriptions := {}; } // The method maintains the invariant that if success is true, then the car parameter is added to the carPark // set and the number of cars in the carPark set is less than the number of normal spaces minus the bad parking // buffer. Otherwise, the carPark and reservedCarPark sets are not modified method enterCarPark(car: string) returns (success: bool) requires true modifies this; ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|carPark|) < normalSpaces - badParkingBuffer); ensures success ==> carPark == old(carPark) + {car}; ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark); ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|carPark|) >= normalSpaces - badParkingBuffer)); ensures subscriptions == old(subscriptions) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend); { if (|carPark| >= normalSpaces - badParkingBuffer || car in carPark || car in reservedCarPark) { return false; } else { carPark := carPark + {car}; return true; } } // The method maintains the invariant that if success is true, then the car parameter is added to the // reservedCarPark set and the number of cars in the reservedCarPark set is less than the number of // reserved spaces and either the weekend variable is true or the car parameter is in the subscriptions set. // Otherwise, the carPark and reservedCarPark sets are not modified method enterReservedCarPark(car: string) returns (success: bool) requires true modifies this; ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|reservedCarPark|) < reservedSpaces) && (car in subscriptions || weekend == true); ensures success ==> reservedCarPark == old(reservedCarPark) + {car}; ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark); ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|reservedCarPark|) >= reservedSpaces) || (car !in subscriptions && weekend == false)); ensures subscriptions == old(subscriptions) && carPark == old(carPark) && weekend == old(weekend); ensures weekend == old(weekend) && subscriptions == old(subscriptions); { if (|reservedCarPark| >= reservedSpaces || car in carPark || car in reservedCarPark || (car !in subscriptions && weekend == false)) { return false; } else { reservedCarPark := reservedCarPark + {car}; return true; } } } method Main() { // Initialises car park with 10 spaces, 3 of which are reserved and therefore 7 are normal var carPark := new CarPark(); // As we are allowing 5 spaces for idiots who can't park within the lines 7 - 5 == 2 var availableSpaces := carPark.checkAvailability(); // Test entering the car park with one car, One space should now be left var success := carPark.enterCarPark("car1"); availableSpaces := carPark.checkAvailability(); // Test entering the car with another car, No spaces should be left success := carPark.enterCarPark("car2"); availableSpaces := carPark.checkAvailability(); // Test entering with another car, should return invalid as carpark is full // normalSpaces = 7, minus 5 spaces because of the bad parking buffer, therefore 2 spaces max success := carPark.enterCarPark("car3"); // Test creating car subscription success := carPark.makeSubscription("car4"); // Test entering the reserved carPark with a valid and an invalid option success := carPark.enterReservedCarPark("car4"); // This car doesn't have a subscription so it should not be successful success := carPark.enterReservedCarPark("car5"); // Test filling the car subscription list success := carPark.makeSubscription("car6"); success := carPark.makeSubscription("car7"); // This won't add as reserved spaces are 3 and we can't have more subscriptions than reserved spaces success := carPark.makeSubscription("car8"); // Test filling reserved car park success := carPark.enterReservedCarPark("car6"); success := carPark.enterReservedCarPark("car7"); // Test leaving car park success := carPark.leaveCarPark("car1"); // Test leaving with car that doesn't exist success := carPark.leaveCarPark("car9"); // Test leaving reserved car park success := carPark.leaveCarPark("car6"); // Testing closing car park, all cars should be destroyed carPark.closeCarPark(); } // Added due to timeout in Main method MainB () { var carPark := new CarPark(); // Test opening the reserved carPark carPark.openReservedArea(); // Test joining carPark on weekend with car without subscription var success := carPark.enterReservedCarPark("car3"); // Testing closing car park, all cars should be destroyed carPark.closeCarPark(); }
009
CS494-final-project_tmp_tmp7nof55uq_bubblesort.dfy
//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 } }
//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 } }
010
CS5232_Project_tmp_tmpai_cfrng_LFUSimple.dfy
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"; }
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"; }
011
CS5232_Project_tmp_tmpai_cfrng_test.dfy
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; } }
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; } }
012
CSC8204-Dafny_tmp_tmp11yhjb53_stack.dfy
/* Dafny Tutorial 2: Sequences and Stacks, Predicates and Assertions In this tutorial we introduce a simple stack model using the functional style of programming. */ type intStack = seq<int> function isEmpty(s: intStack): bool { |s| == 0 } function push(s: intStack, x: int): intStack { s + [x] } function pop(s: intStack): intStack requires !isEmpty(s) { s[..|s|-1] } method testStack() returns (r: intStack) { var s: intStack := [20, 30, 15, 40, 60, 100, 80]; assert pop(push(s,100)) == s; assert forall e: int :: 0 <= e < |s| ==> s[e] > 5; r:= s; } method Main() { var t:=testStack(); print "Stack tested\nStack is ", t, "\n"; }
/* Dafny Tutorial 2: Sequences and Stacks, Predicates and Assertions In this tutorial we introduce a simple stack model using the functional style of programming. */ type intStack = seq<int> function isEmpty(s: intStack): bool { |s| == 0 } function push(s: intStack, x: int): intStack { s + [x] } function pop(s: intStack): intStack requires !isEmpty(s) { s[..|s|-1] } method testStack() returns (r: intStack) { var s: intStack := [20, 30, 15, 40, 60, 100, 80]; r:= s; } method Main() { var t:=testStack(); print "Stack tested\nStack is ", t, "\n"; }
013
CSU55004---Formal-Verification_tmp_tmp4ki9iaqy_Project_Project_Part_1_project_pt_1.dfy
//This method should return true iff pre is a prefix of str. That is, str starts with pre method isPrefix(pre:string, str:string) returns(res:bool) requires 0 < |pre| <= |str| //This line states that this method requires that pre is less than or equal in length to str. Without this line, an out of bounds error is shown on line 14: "str[i] != pre[i]" { //Initialising the index variable var i := 0; //Iterating through the first |pre| elements in str while (i < |pre|) invariant 0 <= i <= |pre| //Specifying the range of the while loop decreases |pre| - i //Specifying that the while loop will terminate { //If an element does not match, return false if (str[i] != pre[i]) { //Debug print print str[i], " != ", pre[i], "\n"; //Return once mismatch detected, no point in iterating any further return false; } //Else loop until mismatch found or we have reached the end of pre else{ //Debug pront print str[i], " == ", pre[i], "\n"; i := i + 1; } } return true; } //This method should return true iff sub is a substring of str. That is, str contains sub method isSubstring(sub:string, str:string) returns(res:bool) requires 0 < |sub| <= |str| //This method requires that sub is less than or equal in length to str { //Initialising the index variable var i := 0; //This variable stores the difference in length between the two strings var n := (|str| - |sub|); //Here, we want to re-use the "isPrefix" method above, so with each iteration of the search, we are passing an offset of str - effectively trimming a character off the front of str and passing it to isPrefix //example 1 (sub found in str): //str = door & sub = or //iteration 1: isPrefix(or, door), returns false, trim & iterate again //iteration 2: isprefix(or, oor), returns false, trim & iterate again //iteration 3: isPrefix(or, or), returns true, stop iterating //example 2 (sub not found in str): //str = doom & sub = or //iteration 1: isPrefix(or, doom), returns false, trim & iterate again //iteration 2: isprefix(or, oom), returns false, trim & iterate again //iteration 3: isPrefix(or, om), returns false, str is has not been "trimmed" to the same length as sub, so we stop iterating while(i < n+1) invariant 0 <= i <= n+1 //Specifying the range of the while loop decreases n - i //Specifying that the while loop will terminate { //Debug print to show what is being passed to isPrefix with each iteration print "\n", sub, ", ", str[i..|str|], "\n"; var result:= isPrefix(sub, str[i..|str|]); //Return once the substring is found, no point in iterating any further if(result == true){ return true; } //Else loop until sub is found, or we have reached the end of str else{ i := i+1; } } return false; } //This method should return true iff str1 and str1 have a common substring of length k method haveCommonKSubstring(k:nat, str1:string, str2:string) returns(found:bool) requires 0 < k <= |str1| && 0 < k <= |str2| //This method requires that k > 0 and k is less than or equal to in length to str1 and str2 { //Initialising the index variable var i := 0; //This variable is used to define the end condition of the while loop var n := |str1|-k; //Here, we want to re-use the "isSubstring" method above, so with each iteration of the search, we are passing a substring of str1 with length k and searching for this substring in str2. If the k-length substring is not found, we "slide" the length-k substring "window" along and search again //example: //str1 = operation, str2 = rational, k = 5 //Iteration 1: isSubstring(opera, rational), returns false, slide the substring & iterate again //Iteration 2: isSubstring(perat, rational), returns false, slide the substring & iterate again //Iteration 3: isSubstring(erati, rational), returns false, slide the substring & iterate again //Iteration 4: isSubstring(ratio, rational), returns true, stop iterating while(i < n) decreases n - i //Specifying that the loop will terminate { //Debug print to show what is being passed to isSubstring with each iteration print "\n", str1[i..i+k], ", ", str2, "\n"; var result := isSubstring(str1[i..i+k], str2); //Return once the length-k substring is found, no point in iterating any further if(result == true){ return true; } //Else loop until the length-k substring is found, or we have reached the end condition else{ i:=i+1; } } return false; } //This method should return the natural number len which is equal to the length of the longest common substring of str1 and str2. Note that every two strings have a common substring of length zero. method maxCommonSubstringLength(str1:string, str2:string) returns(len:nat) requires 0 < |str1| && 0 < |str1| { //This variable is used to store the result of calling haveCommonKSubstring var result:bool; //We want the longest common substring between str1 and str2, so the starting point is going to be the shorter of the two strings. var i:= |str1|; if(|str2| < |str1|){ i := |str2|; } //Here, we want to re-use the "haveKCommonSubstring" method above, so with each iteration of the search, we pass a decreasing value of k until a common substring of this length is found. If no common substring is found, we return 0. while (i > 0) decreases i - 0 { print str1, ", ", str2, " k = ", i, "\n"; result := haveCommonKSubstring(i, str1, str2); if(result == true){ return i; } else{ i := i - 1; } } return 0; } //Main to test each method method Main(){ // isPrefix test var prefix:string := "pre"; var str_1:string := "prehistoric"; var result:bool; /* result := isPrefix(prefix, str_1); if(result == true){ print "TRUE: ", prefix, " is a prefix of the string ", str_1, "\n"; } else{ print "FALSE: ", prefix, " is not a prefix of the string ", str_1, "\n"; } */ // isSubstring test var substring := "and"; var str_2 := "operand"; /* result := isSubstring(substring, str_2); if(result == true){ print "TRUE: ", substring, " is a substring of the string ", str_2, "\n"; } else{ print "FALSE: ", substring, " is not a substring of the string ", str_2, "\n"; } */ // haveCommonKSubstring test //these 2 strings share the common substring "ratio" of length 5 var string1 := "operation"; var string2 := "irrational"; var k:nat := 5; /* result := haveCommonKSubstring(k, string1, string2); if(result == true){ print "TRUE: ", string1, " and ", string2, " have a common substring of length ", k, "\n"; } else{ print "FALSE: ", string1, " and ", string2, " do not have a common substring of length ", k, "\n"; } */ var x := maxCommonSubstringLength(string1, string2); print "Result: ", x, "\n"; }
//This method should return true iff pre is a prefix of str. That is, str starts with pre method isPrefix(pre:string, str:string) returns(res:bool) requires 0 < |pre| <= |str| //This line states that this method requires that pre is less than or equal in length to str. Without this line, an out of bounds error is shown on line 14: "str[i] != pre[i]" { //Initialising the index variable var i := 0; //Iterating through the first |pre| elements in str while (i < |pre|) { //If an element does not match, return false if (str[i] != pre[i]) { //Debug print print str[i], " != ", pre[i], "\n"; //Return once mismatch detected, no point in iterating any further return false; } //Else loop until mismatch found or we have reached the end of pre else{ //Debug pront print str[i], " == ", pre[i], "\n"; i := i + 1; } } return true; } //This method should return true iff sub is a substring of str. That is, str contains sub method isSubstring(sub:string, str:string) returns(res:bool) requires 0 < |sub| <= |str| //This method requires that sub is less than or equal in length to str { //Initialising the index variable var i := 0; //This variable stores the difference in length between the two strings var n := (|str| - |sub|); //Here, we want to re-use the "isPrefix" method above, so with each iteration of the search, we are passing an offset of str - effectively trimming a character off the front of str and passing it to isPrefix //example 1 (sub found in str): //str = door & sub = or //iteration 1: isPrefix(or, door), returns false, trim & iterate again //iteration 2: isprefix(or, oor), returns false, trim & iterate again //iteration 3: isPrefix(or, or), returns true, stop iterating //example 2 (sub not found in str): //str = doom & sub = or //iteration 1: isPrefix(or, doom), returns false, trim & iterate again //iteration 2: isprefix(or, oom), returns false, trim & iterate again //iteration 3: isPrefix(or, om), returns false, str is has not been "trimmed" to the same length as sub, so we stop iterating while(i < n+1) { //Debug print to show what is being passed to isPrefix with each iteration print "\n", sub, ", ", str[i..|str|], "\n"; var result:= isPrefix(sub, str[i..|str|]); //Return once the substring is found, no point in iterating any further if(result == true){ return true; } //Else loop until sub is found, or we have reached the end of str else{ i := i+1; } } return false; } //This method should return true iff str1 and str1 have a common substring of length k method haveCommonKSubstring(k:nat, str1:string, str2:string) returns(found:bool) requires 0 < k <= |str1| && 0 < k <= |str2| //This method requires that k > 0 and k is less than or equal to in length to str1 and str2 { //Initialising the index variable var i := 0; //This variable is used to define the end condition of the while loop var n := |str1|-k; //Here, we want to re-use the "isSubstring" method above, so with each iteration of the search, we are passing a substring of str1 with length k and searching for this substring in str2. If the k-length substring is not found, we "slide" the length-k substring "window" along and search again //example: //str1 = operation, str2 = rational, k = 5 //Iteration 1: isSubstring(opera, rational), returns false, slide the substring & iterate again //Iteration 2: isSubstring(perat, rational), returns false, slide the substring & iterate again //Iteration 3: isSubstring(erati, rational), returns false, slide the substring & iterate again //Iteration 4: isSubstring(ratio, rational), returns true, stop iterating while(i < n) { //Debug print to show what is being passed to isSubstring with each iteration print "\n", str1[i..i+k], ", ", str2, "\n"; var result := isSubstring(str1[i..i+k], str2); //Return once the length-k substring is found, no point in iterating any further if(result == true){ return true; } //Else loop until the length-k substring is found, or we have reached the end condition else{ i:=i+1; } } return false; } //This method should return the natural number len which is equal to the length of the longest common substring of str1 and str2. Note that every two strings have a common substring of length zero. method maxCommonSubstringLength(str1:string, str2:string) returns(len:nat) requires 0 < |str1| && 0 < |str1| { //This variable is used to store the result of calling haveCommonKSubstring var result:bool; //We want the longest common substring between str1 and str2, so the starting point is going to be the shorter of the two strings. var i:= |str1|; if(|str2| < |str1|){ i := |str2|; } //Here, we want to re-use the "haveKCommonSubstring" method above, so with each iteration of the search, we pass a decreasing value of k until a common substring of this length is found. If no common substring is found, we return 0. while (i > 0) { print str1, ", ", str2, " k = ", i, "\n"; result := haveCommonKSubstring(i, str1, str2); if(result == true){ return i; } else{ i := i - 1; } } return 0; } //Main to test each method method Main(){ // isPrefix test var prefix:string := "pre"; var str_1:string := "prehistoric"; var result:bool; /* result := isPrefix(prefix, str_1); if(result == true){ print "TRUE: ", prefix, " is a prefix of the string ", str_1, "\n"; } else{ print "FALSE: ", prefix, " is not a prefix of the string ", str_1, "\n"; } */ // isSubstring test var substring := "and"; var str_2 := "operand"; /* result := isSubstring(substring, str_2); if(result == true){ print "TRUE: ", substring, " is a substring of the string ", str_2, "\n"; } else{ print "FALSE: ", substring, " is not a substring of the string ", str_2, "\n"; } */ // haveCommonKSubstring test //these 2 strings share the common substring "ratio" of length 5 var string1 := "operation"; var string2 := "irrational"; var k:nat := 5; /* result := haveCommonKSubstring(k, string1, string2); if(result == true){ print "TRUE: ", string1, " and ", string2, " have a common substring of length ", k, "\n"; } else{ print "FALSE: ", string1, " and ", string2, " do not have a common substring of length ", k, "\n"; } */ var x := maxCommonSubstringLength(string1, string2); print "Result: ", x, "\n"; }
014
CVS-Projto1_tmp_tmpb1o0bu8z_Hoare.dfy
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; } }
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; } }
015
CVS-Projto1_tmp_tmpb1o0bu8z_fact.dfy
function fact (n:nat): nat decreases n {if n == 0 then 1 else n * fact(n-1)} function factAcc (n:nat, a:int): int decreases n {if (n==0) then a else factAcc(n-1,n*a)} function factAlt(n:nat):int {factAcc(n,1)} lemma factAcc_correct (n:nat, a:int) ensures factAcc(n, a) == a*fact(n) { } lemma factAlt_correct (n:nat) ensures factAlt(n) == fact(n) { factAcc_correct(n,1); assert factAcc(n,1) == 1 * fact(n); assert 1 * fact(n) == fact(n); assert factAlt(n) == factAcc(n, 1); } datatype List<T> = Nil | Cons(T, List<T>) function length<T> (l: List<T>) : nat decreases l { match l case Nil => 0 case Cons(_, r) => 1 + length(r) } lemma {:induction false} length_non_neg<T> (l:List<T>) ensures length(l) >= 0 { match l case Nil => case Cons(_, r) => length_non_neg(r); assert length(r) >= 0; // assert forall k : int :: k >= 0 ==> 1 + k >= 0; assert 1 + length(r) >= 0; assert 1 + length(r) == length(l); } function lengthTL<T> (l: List<T>, acc: nat) : nat { match l case Nil => acc case Cons(_, r) => lengthTL(r, 1 + acc) } lemma {:induction false}lengthTL_aux<T> (l: List<T>, acc: nat) ensures lengthTL(l, acc) == acc + length(l) { match l case Nil => assert acc + length<T>(Nil) == acc; case Cons(_, r) => lengthTL_aux(r, acc + 1); } lemma lengthEq<T> (l: List<T>) ensures length(l) == lengthTL(l,0) { lengthTL_aux(l, 0); }
function fact (n:nat): nat {if n == 0 then 1 else n * fact(n-1)} function factAcc (n:nat, a:int): int {if (n==0) then a else factAcc(n-1,n*a)} function factAlt(n:nat):int {factAcc(n,1)} lemma factAcc_correct (n:nat, a:int) ensures factAcc(n, a) == a*fact(n) { } lemma factAlt_correct (n:nat) ensures factAlt(n) == fact(n) { factAcc_correct(n,1); } datatype List<T> = Nil | Cons(T, List<T>) function length<T> (l: List<T>) : nat { match l case Nil => 0 case Cons(_, r) => 1 + length(r) } lemma {:induction false} length_non_neg<T> (l:List<T>) ensures length(l) >= 0 { match l case Nil => case Cons(_, r) => length_non_neg(r); // assert forall k : int :: k >= 0 ==> 1 + k >= 0; } function lengthTL<T> (l: List<T>, acc: nat) : nat { match l case Nil => acc case Cons(_, r) => lengthTL(r, 1 + acc) } lemma {:induction false}lengthTL_aux<T> (l: List<T>, acc: nat) ensures lengthTL(l, acc) == acc + length(l) { match l case Nil => assert acc + length<T>(Nil) == acc; case Cons(_, r) => lengthTL_aux(r, acc + 1); } lemma lengthEq<T> (l: List<T>) ensures length(l) == lengthTL(l,0) { lengthTL_aux(l, 0); }
016
CVS-Projto1_tmp_tmpb1o0bu8z_proj1_proj1.dfy
//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) }
//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) }
017
CVS-Projto1_tmp_tmpb1o0bu8z_searchSort.dfy
method fillK(a: array<int>, n: int, k: int, c: int) returns (b: bool) requires 0 <= c <= n requires n == a.Length { if c == 0 { return true; } var p := 0; while p < c invariant 0 <= p <= c { if a[p] != k { return false; } p := p + 1; } return true; } method containsSubString(a: array<char>, b: array<char>) returns (pos: int) requires 0 <= b.Length <= a.Length { pos := -1; if b.Length == 0 { return pos; } var p := 0; while p < a.Length invariant 0 <= p <= a.Length { if a.Length - p < b.Length { return pos; } if a[p] == b[0] { var i := 0; while i < b.Length { if a[i + p] != b[i] { return -1; } i:= i + 1; } pos := p; return pos; } p:= p +1; } }
method fillK(a: array<int>, n: int, k: int, c: int) returns (b: bool) requires 0 <= c <= n requires n == a.Length { if c == 0 { return true; } var p := 0; while p < c { if a[p] != k { return false; } p := p + 1; } return true; } method containsSubString(a: array<char>, b: array<char>) returns (pos: int) requires 0 <= b.Length <= a.Length { pos := -1; if b.Length == 0 { return pos; } var p := 0; while p < a.Length { if a.Length - p < b.Length { return pos; } if a[p] == b[0] { var i := 0; while i < b.Length { if a[i + p] != b[i] { return -1; } i:= i + 1; } pos := p; return pos; } p:= p +1; } }
018
CVS-handout1_tmp_tmptm52no3k_1.dfy
/* 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); }
/* 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); }
019
CVS-handout1_tmp_tmptm52no3k_2.dfy
/* 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; }
/* 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; }
020
Clover_abs.dfy
method Abs(x: int) returns (y: int) ensures x>=0 ==> x==y ensures x<0 ==> x+y==0 { if x < 0 { return -x; } else { return x; } }
method Abs(x: int) returns (y: int) ensures x>=0 ==> x==y ensures x<0 ==> x+y==0 { if x < 0 { return -x; } else { return x; } }
021
Clover_all_digits.dfy
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; } } }
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; } } }
022
Clover_array_append.dfy
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; }
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; }
023
Clover_array_concat.dfy
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; } }
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; } }
024
Clover_array_copy.dfy
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; } }
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; } }
025
Clover_array_product.dfy
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; } }
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; } }
026
Clover_array_sum.dfy
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; } }
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; } }
027
Clover_avg.dfy
method ComputeAvg(a: int, b: int) returns (avg:int) ensures avg == (a+b)/2 { avg:= (a + b) / 2; }
method ComputeAvg(a: int, b: int) returns (avg:int) ensures avg == (a+b)/2 { avg:= (a + b) / 2; }
028
Clover_below_zero.dfy
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; } }
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; } }
029
Clover_binary_search.dfy
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; }
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; }
030
Clover_bubble_sort.dfy
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; } }
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; } }
031
Clover_cal_ans.dfy
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; } }
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; } }
032
Clover_cal_sum.dfy
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; } }
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; } }
033
Clover_canyon_search.dfy
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; } }
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; } }
034
Clover_compare.dfy
method Compare<T(==)>(a: T, b: T) returns (eq: bool) ensures a==b ==> eq==true ensures a!=b ==> eq==false { if a == b { eq := true; } else { eq := false; } }
method Compare<T(==)>(a: T, b: T) returns (eq: bool) ensures a==b ==> eq==true ensures a!=b ==> eq==false { if a == b { eq := true; } else { eq := false; } }
035
Clover_convert_map_key.dfy
method convert_map_key(inputs: map<nat, bool>, f: nat->nat) returns(r:map<nat, bool>) requires forall n1: nat, n2: nat :: n1 != n2 ==> f(n1) != f(n2) ensures forall k :: k in inputs <==> f(k) in r ensures forall k :: k in inputs ==> r[f(k)] == inputs[k] { r:= map k | k in inputs :: f(k) := inputs[k]; }
method convert_map_key(inputs: map<nat, bool>, f: nat->nat) returns(r:map<nat, bool>) requires forall n1: nat, n2: nat :: n1 != n2 ==> f(n1) != f(n2) ensures forall k :: k in inputs <==> f(k) in r ensures forall k :: k in inputs ==> r[f(k)] == inputs[k] { r:= map k | k in inputs :: f(k) := inputs[k]; }
036
Clover_copy_part.dfy
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; } }
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; } }
037
Clover_count_lessthan.dfy
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; } } }
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; } } }
038
Clover_double_array_elements.dfy
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; } }
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; } }
039
Clover_double_quadruple.dfy
method DoubleQuadruple(x: int) returns (a: int, b: int) ensures a == 2 * x && b == 4 * x { a := 2 * x; b := 2 * a; }
method DoubleQuadruple(x: int) returns (a: int, b: int) ensures a == 2 * x && b == 4 * x { a := 2 * x; b := 2 * a; }
040
Clover_even_list.dfy
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[..]; }
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]); }
041
Clover_find.dfy
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; } }
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; } }
042
Clover_has_close_elements.dfy
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; } }
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; } }
043
Clover_insert.dfy
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]; }
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; } }
044
Clover_integer_square_root.dfy
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; } }
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; } }
045
Clover_is_even.dfy
method ComputeIsEven(x:int) returns (is_even:bool) ensures (x % 2 == 0)==is_even { is_even:=false; if x%2==0{ is_even:=true; } }
method ComputeIsEven(x:int) returns (is_even:bool) ensures (x % 2 == 0)==is_even { is_even:=false; if x%2==0{ is_even:=true; } }
046
Clover_is_palindrome.dfy
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; } }
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; } }
047
Clover_linear_search1.dfy
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; } }
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; } }
048
Clover_linear_search2.dfy
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; } }
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; } }
049
Clover_linear_search3.dfy
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; } }
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; } }
050
Clover_longest_prefix.dfy
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]]; } }
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]]; } }
051
Clover_match.dfy
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; }
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; }
052
Clover_max_array.dfy
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; } }
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; } }
053
Clover_min_array.dfy
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; } }
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; } }
054
Clover_min_of_two.dfy
method Min(x: int, y:int) returns (z: int) ensures x<=y ==> z==x ensures x>y ==> z==y { if x < y { return x; } else { return y; } }
method Min(x: int, y:int) returns (z: int) ensures x<=y ==> z==x ensures x>y ==> z==y { if x < y { return x; } else { return y; } }
055
Clover_modify_2d_array.dfy
method modify_array_element(arr: array<array<nat>>, index1: nat, index2: nat, val: nat) requires index1 < arr.Length requires index2 < arr[index1].Length requires forall i: nat, j:nat :: i < arr.Length && j < arr.Length && i != j ==> arr[i] != arr[j] modifies arr[index1] ensures forall i: nat :: 0 <= i < arr.Length ==> arr[i] == old(arr[i]) ensures forall i: nat, j: nat :: 0 <= i < arr.Length && 0 <= j < arr[i].Length && (i != index1 || j != index2) ==> arr[i][j] == old(arr[i][j]) ensures arr[index1][index2] == val { arr[index1][index2] := val; }
method modify_array_element(arr: array<array<nat>>, index1: nat, index2: nat, val: nat) requires index1 < arr.Length requires index2 < arr[index1].Length requires forall i: nat, j:nat :: i < arr.Length && j < arr.Length && i != j ==> arr[i] != arr[j] modifies arr[index1] ensures forall i: nat :: 0 <= i < arr.Length ==> arr[i] == old(arr[i]) ensures forall i: nat, j: nat :: 0 <= i < arr.Length && 0 <= j < arr[i].Length && (i != index1 || j != index2) ==> arr[i][j] == old(arr[i][j]) ensures arr[index1][index2] == val { arr[index1][index2] := val; }
056
Clover_multi_return.dfy
method MultipleReturns(x: int, y: int) returns (more: int, less: int) ensures more == x+y ensures less == x-y { more := x + y; less := x - y; }
method MultipleReturns(x: int, y: int) returns (more: int, less: int) ensures more == x+y ensures less == x-y { more := x + y; less := x - y; }
057
Clover_online_max.dfy
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; }
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; }
058
Clover_only_once.dfy
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[..]; }
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; } }
059
Clover_quotient.dfy
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; } }
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; } }
060
Clover_remove_front.dfy
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; } }
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; } }
061
Clover_replace.dfy
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; } }
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; } }
062
Clover_return_seven.dfy
method M(x: int) returns (seven: int) ensures seven==7 { seven := 7; }
method M(x: int) returns (seven: int) ensures seven==7 { seven := 7; }
063
Clover_reverse.dfy
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; } }
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; } }
064
Clover_rotate.dfy
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; } }
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; } }
065
Clover_selectionsort.dfy
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; } }
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; } }
066
Clover_seq_to_array.dfy
method ToArray<T>(xs: seq<T>) returns (a: array<T>) ensures fresh(a) ensures a.Length == |xs| ensures forall i :: 0 <= i < |xs| ==> a[i] == xs[i] { a := new T[|xs|](i requires 0 <= i < |xs| => xs[i]); }
method ToArray<T>(xs: seq<T>) returns (a: array<T>) ensures fresh(a) ensures a.Length == |xs| ensures forall i :: 0 <= i < |xs| ==> a[i] == xs[i] { a := new T[|xs|](i requires 0 <= i < |xs| => xs[i]); }
067
Clover_set_to_seq.dfy
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]; } }
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]; } }
068
Clover_slope_search.dfy
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; } } }
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; } } }
069
Clover_swap.dfy
method Swap(X: int, Y: int) returns(x: int, y: int) ensures x==Y ensures y==X { x, y := X, Y; var tmp := x; x := y; y := tmp; assert x == Y && y == X; }
method Swap(X: int, Y: int) returns(x: int, y: int) ensures x==Y ensures y==X { x, y := X, Y; var tmp := x; x := y; y := tmp; }
070
Clover_swap_arith.dfy
method SwapArithmetic(X: int, Y: int) returns(x: int, y: int) ensures x==Y ensures y==X { x, y := X, Y; x := y - x; y := y - x; x := y + x; }
method SwapArithmetic(X: int, Y: int) returns(x: int, y: int) ensures x==Y ensures y==X { x, y := X, Y; x := y - x; y := y - x; x := y + x; }
071
Clover_swap_bitvector.dfy
method SwapBitvectors(X: bv8, Y: bv8) returns(x: bv8, y: bv8) ensures x==Y ensures y==X { x, y := X, Y; x := x ^ y; y := x ^ y; x := x ^ y; }
method SwapBitvectors(X: bv8, Y: bv8) returns(x: bv8, y: bv8) ensures x==Y ensures y==X { x, y := X, Y; x := x ^ y; y := x ^ y; x := x ^ y; }
072
Clover_swap_in_array.dfy
method swap(arr: array<int>, i: int, j: int) requires 0 <= i < arr.Length && 0 <= j < arr.Length modifies arr ensures arr[i] == old(arr[j]) && arr[j] == old(arr[i]) ensures forall k :: 0 <= k < arr.Length && k != i && k != j ==> arr[k] == old(arr[k]) { var tmp := arr[i]; arr[i] := arr[j]; arr[j] := tmp; }
method swap(arr: array<int>, i: int, j: int) requires 0 <= i < arr.Length && 0 <= j < arr.Length modifies arr ensures arr[i] == old(arr[j]) && arr[j] == old(arr[i]) ensures forall k :: 0 <= k < arr.Length && k != i && k != j ==> arr[k] == old(arr[k]) { var tmp := arr[i]; arr[i] := arr[j]; arr[j] := tmp; }
073
Clover_swap_sim.dfy
method SwapSimultaneous(X: int, Y: int) returns(x: int, y: int) ensures x==Y ensures y==X { x, y := X, Y; x, y := y, x; }
method SwapSimultaneous(X: int, Y: int) returns(x: int, y: int) ensures x==Y ensures y==X { x, y := X, Y; x, y := y, x; }
074
Clover_test_array.dfy
method TestArrayElements(a:array<int>, j: nat) requires 0<=j < a.Length modifies a ensures a[j] == 60 ensures forall k :: 0 <= k < a.Length && k != j ==> a[k] == old(a[k]) { a[j] := 60; }
method TestArrayElements(a:array<int>, j: nat) requires 0<=j < a.Length modifies a ensures a[j] == 60 ensures forall k :: 0 <= k < a.Length && k != j ==> a[k] == old(a[k]) { a[j] := 60; }
075
Clover_triple.dfy
method Triple (x:int) returns (r:int) ensures r==3*x { r:= x*3; }
method Triple (x:int) returns (r:int) ensures r==3*x { r:= x*3; }
076
Clover_triple2.dfy
method Triple (x:int) returns (r:int) ensures r==3*x { if { case x<18 => var a,b := 2*x, 4*x; r:=(a+b)/2; case 0<=x => var y:=2*x; r:= x+y; } }
method Triple (x:int) returns (r:int) ensures r==3*x { if { case x<18 => var a,b := 2*x, 4*x; r:=(a+b)/2; case 0<=x => var y:=2*x; r:= x+y; } }
077
Clover_triple3.dfy
method Triple (x:int) returns (r:int) ensures r==3*x { if x==0 { r:=0; } else{ var y:=2*x; r:= x+y; } }
method Triple (x:int) returns (r:int) ensures r==3*x { if x==0 { r:=0; } else{ var y:=2*x; r:= x+y; } }
078
Clover_triple4.dfy
method Triple (x:int) returns (r:int) ensures r==3*x { var y:= x*2; r := y+x; }
method Triple (x:int) returns (r:int) ensures r==3*x { var y:= x*2; r := y+x; }
079
Clover_two_sum.dfy
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; } }
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; } }
080
Clover_update_array.dfy
method UpdateElements(a: array<int>) requires a.Length >= 8 modifies a ensures old(a[4]) +3 == a[4] ensures a[7]==516 ensures forall i::0 <= i<a.Length ==> i != 7 && i != 4 ==> a[i] == old(a[i]) { a[4] := a[4] + 3; a[7] := 516; }
method UpdateElements(a: array<int>) requires a.Length >= 8 modifies a ensures old(a[4]) +3 == a[4] ensures a[7]==516 ensures forall i::0 <= i<a.Length ==> i != 7 && i != 4 ==> a[i] == old(a[i]) { a[4] := a[4] + 3; a[7] := 516; }
081
Clover_update_map.dfy
method update_map<K(!new), V>(m1: map<K, V>, m2: map<K, V>) returns (r: map<K, V>) ensures (forall k :: k in m2 ==> k in r) ensures (forall k :: k in m1 ==> k in r) ensures (forall k :: k in m2 ==> r[k] == m2[k]) ensures (forall k :: !(k in m2) && k in m1 ==> r[k] == m1[k]) ensures (forall k :: !(k in m2) && !(k in m1) ==> !(k in r)) { r:= map k | k in (m1.Keys + m2.Keys) :: if k in m2 then m2[k] else m1[k]; }
method update_map<K(!new), V>(m1: map<K, V>, m2: map<K, V>) returns (r: map<K, V>) ensures (forall k :: k in m2 ==> k in r) ensures (forall k :: k in m1 ==> k in r) ensures (forall k :: k in m2 ==> r[k] == m2[k]) ensures (forall k :: !(k in m2) && k in m1 ==> r[k] == m1[k]) ensures (forall k :: !(k in m2) && !(k in m1) ==> !(k in r)) { r:= map k | k in (m1.Keys + m2.Keys) :: if k in m2 then m2[k] else m1[k]; }
082
Correctness_tmp_tmpwqvg5q_4_HoareLogic_exam.dfy
// 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; }
// 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; }
083
Correctness_tmp_tmpwqvg5q_4_MethodCalls_q1.dfy
/** (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); }
/** (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(); }
084
Correctness_tmp_tmpwqvg5q_4_Sorting_Tangent.dfy
/** 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 }
/** 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 }
085
Dafny-Exercises_tmp_tmpjm75muf__Session10Exercises_ExerciseBarrier.dfy
//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; }
//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; }
086
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseExp.dfy
function exp(x:int, e:int):int decreases e requires e >= 0 ensures x > 0 ==> exp(x,e) > 0 { if e == 0 then 1 else x*exp(x,e-1) } lemma exp3_Lemma(n:int) decreases n requires n >= 1 ensures (exp(3,n)-1)%2 == 0 {} lemma mult8_Lemma(n:int) decreases n requires n >= 1 ensures (exp(3,2*n) - 1)%8 == 0 { if(n==1){ } else{ calc =={ (exp(3,2*n) -1) % 8; (exp(3, 2*(n-1)) *8 + exp(3,2*(n-1)) - 1) % 8; { mult8_Lemma(n-1); assert exp(3,2*(n-1)) * 8 %8==0; } 0; } } }
function exp(x:int, e:int):int requires e >= 0 ensures x > 0 ==> exp(x,e) > 0 { if e == 0 then 1 else x*exp(x,e-1) } lemma exp3_Lemma(n:int) requires n >= 1 ensures (exp(3,n)-1)%2 == 0 {} lemma mult8_Lemma(n:int) requires n >= 1 ensures (exp(3,2*n) - 1)%8 == 0 { if(n==1){ } else{ calc =={ (exp(3,2*n) -1) % 8; (exp(3, 2*(n-1)) *8 + exp(3,2*(n-1)) - 1) % 8; { mult8_Lemma(n-1); } 0; } } }
087
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseFibonacci.dfy
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; } } }
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; } } }
088
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExercisePositive.dfy
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; }
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; }
089
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseSquare_root.dfy
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;} } }
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;} } }
090
Dafny-Exercises_tmp_tmpjm75muf__Session3Exercises_ExerciseMaximum.dfy
//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]; }
//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]; }
091
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseAllEqual.dfy
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;} } }
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;} } }
092
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseContained.dfy
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; }
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; }
093
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseFirstNegative.dfy
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;} } }
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;} } }
094
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExercisefirstZero.dfy
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;} }
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;} }
095
Dafny-Exercises_tmp_tmpjm75muf__Session5Exercises_ExerciseSumElems.dfy
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; } }
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; } }
096
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExerciseCountEven.dfy
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; } }
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; } }
097
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExerciseCountMin.dfy
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; } }
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; } }
098
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExercisePeekSum.dfy
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; } }
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; } }
099
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBinarySearch.dfy
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; } }
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; } }