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; } }
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card