Dataset Viewer
id
stringlengths 3
3
| name
stringlengths 3
3
| docstring
stringlengths 18
18
| code
stringlengths 129
20.6k
| ground_truth
stringlengths 148
21.8k
| test_file
stringlengths 15
119
|
|---|---|---|---|---|---|
000
|
000
|
Dafny program: 000
|
function sorted(a: array<int>) : bool
reads a
{
forall i,j : int :: 0 <= i < j < a.Length ==> a[i] <= a[j]
}
method BinarySearch(a: array<int>, x: int) returns (index: int)
requires sorted(a)
ensures 0 <= index < a.Length ==> a[index] == x
ensures index == -1 ==> forall i : int :: 0 <= i < a.Length ==> a[i] != x
{
var low := 0;
var high := a.Length - 1;
var mid := 0;
while (low <= high)
{
mid := (high + low) / 2;
if a[mid] < x {
low := mid + 1;
}
else if a[mid] > x {
high := mid - 1;
}
else {
return mid;
}
}
return -1;
}
|
function sorted(a: array<int>) : bool
reads a
{
forall i,j : int :: 0 <= i < j < a.Length ==> a[i] <= a[j]
}
method BinarySearch(a: array<int>, x: int) returns (index: int)
requires sorted(a)
ensures 0 <= index < a.Length ==> a[index] == x
ensures index == -1 ==> forall i : int :: 0 <= i < a.Length ==> a[i] != x
{
var low := 0;
var high := a.Length - 1;
var mid := 0;
while (low <= high)
invariant 0 <= low <= high + 1 <= a.Length
invariant x !in a[..low] && x !in a[high + 1..]
{
mid := (high + low) / 2;
if a[mid] < x {
low := mid + 1;
}
else if a[mid] > x {
high := mid - 1;
}
else {
return mid;
}
}
return -1;
}
|
630-dafny_tmp_tmpz2kokaiq_Solution.dfy
|
003
|
003
|
Dafny program: 003
|
// Noa Leron 207131871
// Tsuri Farhana 315016907
// definitions borrowed from Rustan Leino's Program Proofs Chapter 7
// (https://program-proofs.com/code.html example code in Dafny; source file 7-Unary.dfy)
datatype Unary = Zero | Suc(pred: Unary)
ghost function UnaryToNat(x: Unary): nat {
match x
case Zero => 0
case Suc(x') => 1 + UnaryToNat(x')
}
ghost function NatToUnary(n: nat): Unary {
if n == 0 then Zero else Suc(NatToUnary(n-1))
}
lemma NatUnaryCorrespondence(n: nat, x: Unary)
ensures UnaryToNat(NatToUnary(n)) == n
ensures NatToUnary(UnaryToNat(x)) == x
{
}
predicate Less(x: Unary, y: Unary) {
y != Zero && (x.Suc? ==> Less(x.pred, y.pred))
}
predicate LessAlt(x: Unary, y: Unary) {
y != Zero && (x == Zero || Less(x.pred, y.pred))
}
lemma LessSame(x: Unary, y: Unary)
ensures Less(x, y) == LessAlt(x, y)
{
}
lemma LessCorrect(x: Unary, y: Unary)
ensures Less(x, y) <==> UnaryToNat(x) < UnaryToNat(y)
{
}
lemma LessTransitive(x: Unary, y: Unary, z: Unary)
requires Less(x, y) && Less(y, z)
ensures Less(x, z)
{
}
function Add(x: Unary, y: Unary): Unary {
match y
case Zero => x
case Suc(y') => Suc(Add(x, y'))
}
lemma {:induction false} SucAdd(x: Unary, y: Unary)
ensures Suc(Add(x, y)) == Add(Suc(x), y)
{
match y
case Zero =>
case Suc(y') =>
calc {
Suc(Add(x, Suc(y')));
== // def. Add
Suc(Suc(Add(x, y')));
== { SucAdd(x, y'); }
Suc(Add(Suc(x), y'));
== // def. Add
Add(Suc(x), Suc(y'));
}
}
lemma {:induction false} AddZero(x: Unary)
ensures Add(Zero, x) == x
{
match x
case Zero =>
case Suc(x') =>
calc {
Add(Zero, Suc(x'));
== // def. Add
Suc(Add(Zero, x'));
== { AddZero(x'); }
Suc(x');
}
}
function Sub(x: Unary, y: Unary): Unary
requires !Less(x, y)
{
match y
case Zero => x
case Suc(y') => Sub(x.pred, y')
}
function Mul(x: Unary, y: Unary): Unary {
match x
case Zero => Zero
case Suc(x') => Add(Mul(x', y), y)
}
lemma SubStructurallySmaller(x: Unary, y: Unary)
requires !Less(x, y) && y != Zero
ensures Sub(x, y) < x
{
}
lemma AddSub(x: Unary, y: Unary)
requires !Less(x, y)
ensures Add(Sub(x, y), y) == x
{
}
/*
Goal: implement correcly and clearly, using iterative code (no recursion), documenting the proof obligations
as we've learned, with assertions and a lemma for each proof goal
- DO NOT modify the specification or any of the definitions given in this file
- Not all definitions above are relevant, some are simply included as examples
- Feel free to use existing non-ghost functions/predicates in your code, and existing lemmas (for the proof) in your annotations
- New functions/predicates may be added ONLY as ghost
- If it helps you in any way, a recursive implementation + proof can be found in the book and the downloadable source file
[https://program-proofs.com/code.html example code in Dafny, source file 7-Unary.dfy]
*/
method{:verify false} IterativeDivMod'(x: Unary, y: Unary) returns (d: Unary, m: Unary)
requires y != Zero
ensures Add(Mul(d, y), m) == x && Less(m, y)
{
if (Less(x, y)) {
d := Zero;
m := x;
}
else{
var x0: Unary := x;
d := Zero;
while (!Less(x0, y))
{
d := Suc(d);
x0 := Sub(x0, y);
}
m := x0;
}
}
method IterativeDivMod(x: Unary, y: Unary) returns (d: Unary, m: Unary)
requires y != Zero
ensures Add(Mul(d, y), m) == x && Less(m, y)
{
if (Less(x, y)) {
AddZero(x);
d := Zero;
m := x;
}
else{
var x0: Unary := x;
d := Zero;
AddZero(x);
while (!Less(x0, y))
{
AddMulSucSubEqAddMul(d, y , x0);
d := Suc(d);
SubStructurallySmaller(x0, y);
x0 := Sub(x0, y);
}
m := x0;
}
}
lemma AddMulEqMulSuc(a: Unary, b: Unary)
ensures Mul(Suc(a), b) == Add(Mul(a, b), b)
{
calc{
Mul(Suc(a), b);
== // def. Mul
Add(Mul(a, b), b);
}
}
lemma AddMulSucSubEqAddMul(d: Unary, y: Unary, x0: Unary)
requires !Less(x0, y)
requires y != Zero
ensures Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0)
{
calc{
Add(Mul(Suc(d), y), Sub(x0, y));
== {AddMulEqMulSuc(d, y);
Add(Add(Mul(d, y), y), Sub(x0, y));
== {AddTransitive(Mul(d, y), y, Sub(x0, y));
Add(Mul(d, y), Add(y, Sub(x0, y)));
== {AddCommutative(Sub(x0, y), y);
Add(Mul(d, y), Add(Sub(x0, y), y));
== {assert !Less(x0, y);
AddSub(x0, y);
Add(Mul(d, y), x0);
}
}
lemma AddTransitive(a: Unary, b: Unary, c: Unary)
ensures Add(a, Add(b, c)) == Add(Add(a, b), c)
{//These assertions are only for documanting the proof obligations
match c
case Zero =>
calc{
Add(a, Add(b, c));
==
Add(a, Add(b, Zero));
== // def. Add
Add(a, b);
== // def. Add
Add(Add(a,b), Zero);
==
Add(Add(a,b), c);
}
case Suc(c') =>
match b
case Zero =>
calc{
Add(a, Add(b, c));
==
Add(a, Add(Zero, Suc(c')));
== {AddZero(Suc(c'));
Add(a, Suc(c'));
== // def. Add
Add(Add(a, Zero), Suc(c'));
==
Add(Add(a, b), Suc(c'));
==
Add(Add(a,b), c);
}
case Suc(b') =>
match a
case Zero =>
calc{
Add(a, Add(b, c));
==
Add(Zero, Add(Suc(b'), Suc(c')));
== {AddZero(Add(Suc(b'), Suc(c')));
Add(Suc(b'), Suc(c'));
== {AddZero(Suc(b'));
Add(Add(Zero, Suc(b')), Suc(c'));
==
Add(Add(a, b), c);
}
case Suc(a') =>
calc{
Add(a, Add(b, c));
==
Add(Suc(a'), Add(Suc(b'), Suc(c')));
== // def. Add
Add(Suc(a'), Suc(Add(Suc(b'), c')));
== // def. Add
Suc(Add(Suc(a'), Add(Suc(b'), c')));
== {SucAdd(a', Add(Suc(b'), c'));
Suc(Suc(Add(a', Add(Suc(b'), c'))));
== {SucAdd(b', c');
Suc(Suc(Add(a', Suc(Add(b', c')))));
== // def. Add
Suc(Suc(Suc(Add(a', Add(b', c')))));
== {AddTransitive(a', b', c');
Suc(Suc(Suc(Add(Add(a',b'), c'))));
== // def. Add
Suc(Suc(Add(Add(a', b'), Suc(c'))));
== {SucAdd(Add(a', b'), Suc(c'));
Suc(Add(Suc(Add(a', b')), Suc(c')));
== {SucAdd(a', b');
Suc(Add(Add(Suc(a'), b'), Suc(c')));
== {SucAdd(Add(Suc(a'), b'), Suc(c'));
Add(Suc(Add(Suc(a'), b')), Suc(c'));
== // def. Add
Add(Add(Suc(a'), Suc(b')), Suc(c'));
==
Add(Add(a,b), c);
}
}
lemma AddCommutative(a: Unary, b: Unary)
ensures Add(a, b) == Add(b, a)
{
match b
case Zero =>
calc{
Add(a, b);
==
Add(a, Zero);
== // def. Add
a;
== {AddZero(a);
Add(Zero, a);
==
Add(b, a);
}
case Suc(b') =>
calc{
Add(a, b);
==
Add(a, Suc(b'));
== // def. Add
Suc(Add(a, b'));
== {AddCommutative(a, b');
Suc(Add(b', a));
== {SucAdd(b', a);
Add(Suc(b'), a);
==
Add(b, a);
}
}
method Main() {
var U3 := Suc(Suc(Suc(Zero)));
var U7 := Suc(Suc(Suc(Suc(U3))));
var d, m := IterativeDivMod(U7, U3);
print "Just as 7 divided by 3 is 2 with a remainder of 1, IterativeDivMod(", U7, ", ", U3, ") is ", d, " with a remainder of ", m;
}
|
// Noa Leron 207131871
// Tsuri Farhana 315016907
// definitions borrowed from Rustan Leino's Program Proofs Chapter 7
// (https://program-proofs.com/code.html example code in Dafny; source file 7-Unary.dfy)
datatype Unary = Zero | Suc(pred: Unary)
ghost function UnaryToNat(x: Unary): nat {
match x
case Zero => 0
case Suc(x') => 1 + UnaryToNat(x')
}
ghost function NatToUnary(n: nat): Unary {
if n == 0 then Zero else Suc(NatToUnary(n-1))
}
lemma NatUnaryCorrespondence(n: nat, x: Unary)
ensures UnaryToNat(NatToUnary(n)) == n
ensures NatToUnary(UnaryToNat(x)) == x
{
}
predicate Less(x: Unary, y: Unary) {
y != Zero && (x.Suc? ==> Less(x.pred, y.pred))
}
predicate LessAlt(x: Unary, y: Unary) {
y != Zero && (x == Zero || Less(x.pred, y.pred))
}
lemma LessSame(x: Unary, y: Unary)
ensures Less(x, y) == LessAlt(x, y)
{
}
lemma LessCorrect(x: Unary, y: Unary)
ensures Less(x, y) <==> UnaryToNat(x) < UnaryToNat(y)
{
}
lemma LessTransitive(x: Unary, y: Unary, z: Unary)
requires Less(x, y) && Less(y, z)
ensures Less(x, z)
{
}
function Add(x: Unary, y: Unary): Unary {
match y
case Zero => x
case Suc(y') => Suc(Add(x, y'))
}
lemma {:induction false} SucAdd(x: Unary, y: Unary)
ensures Suc(Add(x, y)) == Add(Suc(x), y)
{
match y
case Zero =>
case Suc(y') =>
calc {
Suc(Add(x, Suc(y')));
== // def. Add
Suc(Suc(Add(x, y')));
== { SucAdd(x, y'); }
Suc(Add(Suc(x), y'));
== // def. Add
Add(Suc(x), Suc(y'));
}
}
lemma {:induction false} AddZero(x: Unary)
ensures Add(Zero, x) == x
{
match x
case Zero =>
case Suc(x') =>
calc {
Add(Zero, Suc(x'));
== // def. Add
Suc(Add(Zero, x'));
== { AddZero(x'); }
Suc(x');
}
}
function Sub(x: Unary, y: Unary): Unary
requires !Less(x, y)
{
match y
case Zero => x
case Suc(y') => Sub(x.pred, y')
}
function Mul(x: Unary, y: Unary): Unary {
match x
case Zero => Zero
case Suc(x') => Add(Mul(x', y), y)
}
lemma SubStructurallySmaller(x: Unary, y: Unary)
requires !Less(x, y) && y != Zero
ensures Sub(x, y) < x
{
}
lemma AddSub(x: Unary, y: Unary)
requires !Less(x, y)
ensures Add(Sub(x, y), y) == x
{
}
/*
Goal: implement correcly and clearly, using iterative code (no recursion), documenting the proof obligations
as we've learned, with assertions and a lemma for each proof goal
- DO NOT modify the specification or any of the definitions given in this file
- Not all definitions above are relevant, some are simply included as examples
- Feel free to use existing non-ghost functions/predicates in your code, and existing lemmas (for the proof) in your annotations
- New functions/predicates may be added ONLY as ghost
- If it helps you in any way, a recursive implementation + proof can be found in the book and the downloadable source file
[https://program-proofs.com/code.html example code in Dafny, source file 7-Unary.dfy]
*/
method{:verify false} IterativeDivMod'(x: Unary, y: Unary) returns (d: Unary, m: Unary)
requires y != Zero
ensures Add(Mul(d, y), m) == x && Less(m, y)
{
if (Less(x, y)) {
d := Zero;
m := x;
}
else{
var x0: Unary := x;
d := Zero;
while (!Less(x0, y))
invariant Add(Mul(d, y), x0) == x
decreases x0
{
d := Suc(d);
x0 := Sub(x0, y);
}
m := x0;
}
}
method IterativeDivMod(x: Unary, y: Unary) returns (d: Unary, m: Unary)
requires y != Zero
ensures Add(Mul(d, y), m) == x && Less(m, y)
{
if (Less(x, y)) {
assert Less(x, y);
AddZero(x);
assert Add(Zero, x) == x;
assert Mul(Zero, y) == Zero;
assert Add(Mul(Zero, y), x) == x;
d := Zero;
m := x;
assert Add(Mul(d, y), m) == m;
assert Less(m, y);
assert Add(Mul(d, y), m) == x && Less(m, y);
}
else{
assert !Less(x, y);
assert y != Zero;
var x0: Unary := x;
assert Mul(Zero, y) == Zero;
d := Zero;
assert Mul(d, y) == Zero;
AddZero(x);
assert Add(Zero, x) == x;
assert Add(Mul(d, y), x) == x;
assert Add(Mul(d, y), x0) == x;
while (!Less(x0, y))
invariant Add(Mul(d, y), x0) == x
decreases x0
{
assert Add(Mul(d, y), x0) == x;
assert !Less(x0, y);
assert y != Zero;
AddMulSucSubEqAddMul(d, y , x0);
assert Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0);
assert Add(Mul(Suc(d), y), Sub(x0, y)) == x;
d := Suc(d);
assert !Less(x0, y) && y != Zero;
SubStructurallySmaller(x0, y);
assert Sub(x0, y) < x0; // decreases
x0 := Sub(x0, y);
assert Add(Mul(d, y), x0) == x;
}
assert Add(Mul(d, y), x0) == x;
m := x0;
assert Add(Mul(d, y), m) == x;
}
assert Add(Mul(d, y), m) == x;
}
lemma AddMulEqMulSuc(a: Unary, b: Unary)
ensures Mul(Suc(a), b) == Add(Mul(a, b), b)
{
calc{
Mul(Suc(a), b);
== // def. Mul
Add(Mul(a, b), b);
}
}
lemma AddMulSucSubEqAddMul(d: Unary, y: Unary, x0: Unary)
requires !Less(x0, y)
requires y != Zero
ensures Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0)
{
calc{
Add(Mul(Suc(d), y), Sub(x0, y));
== {AddMulEqMulSuc(d, y);
assert Mul(Suc(d), y) == Add(Mul(d, y), y);}
Add(Add(Mul(d, y), y), Sub(x0, y));
== {AddTransitive(Mul(d, y), y, Sub(x0, y));
assert Add(Mul(d, y), Add(y, Sub(x0, y))) == Add(Add(Mul(d, y), y), Sub(x0, y));}
Add(Mul(d, y), Add(y, Sub(x0, y)));
== {AddCommutative(Sub(x0, y), y);
assert Add(Sub(x0, y), y) == Add(y, Sub(x0, y));}
Add(Mul(d, y), Add(Sub(x0, y), y));
== {assert !Less(x0, y);
AddSub(x0, y);
assert Add(Sub(x0, y), y) == x0;}
Add(Mul(d, y), x0);
}
}
lemma AddTransitive(a: Unary, b: Unary, c: Unary)
ensures Add(a, Add(b, c)) == Add(Add(a, b), c)
{//These assertions are only for documanting the proof obligations
match c
case Zero =>
calc{
Add(a, Add(b, c));
==
Add(a, Add(b, Zero));
== // def. Add
Add(a, b);
== // def. Add
Add(Add(a,b), Zero);
==
Add(Add(a,b), c);
}
case Suc(c') =>
match b
case Zero =>
calc{
Add(a, Add(b, c));
==
Add(a, Add(Zero, Suc(c')));
== {AddZero(Suc(c'));
assert Add(Zero, Suc(c')) == Suc(c');}
Add(a, Suc(c'));
== // def. Add
Add(Add(a, Zero), Suc(c'));
==
Add(Add(a, b), Suc(c'));
==
Add(Add(a,b), c);
}
case Suc(b') =>
match a
case Zero =>
calc{
Add(a, Add(b, c));
==
Add(Zero, Add(Suc(b'), Suc(c')));
== {AddZero(Add(Suc(b'), Suc(c')));
assert Add(Zero, Add(Suc(b'), Suc(c'))) == Add(Suc(b'), Suc(c'));}
Add(Suc(b'), Suc(c'));
== {AddZero(Suc(b'));
assert Add(Zero , Suc(b')) == Suc(b');}
Add(Add(Zero, Suc(b')), Suc(c'));
==
Add(Add(a, b), c);
}
case Suc(a') =>
calc{
Add(a, Add(b, c));
==
Add(Suc(a'), Add(Suc(b'), Suc(c')));
== // def. Add
Add(Suc(a'), Suc(Add(Suc(b'), c')));
== // def. Add
Suc(Add(Suc(a'), Add(Suc(b'), c')));
== {SucAdd(a', Add(Suc(b'), c'));
assert Suc(Add(a', Add(Suc(b'), c'))) == Add(Suc(a'), Add(Suc(b'), c'));}
Suc(Suc(Add(a', Add(Suc(b'), c'))));
== {SucAdd(b', c');
assert Suc(Add(b', c')) == Add(Suc(b'), c');}
Suc(Suc(Add(a', Suc(Add(b', c')))));
== // def. Add
Suc(Suc(Suc(Add(a', Add(b', c')))));
== {AddTransitive(a', b', c');
assert Add(a', Add(b',c')) == Add(Add(a',b'),c');}
Suc(Suc(Suc(Add(Add(a',b'), c'))));
== // def. Add
Suc(Suc(Add(Add(a', b'), Suc(c'))));
== {SucAdd(Add(a', b'), Suc(c'));
assert Suc(Add(Add(a', b'), Suc(c'))) == Add(Suc(Add(a', b')), Suc(c'));}
Suc(Add(Suc(Add(a', b')), Suc(c')));
== {SucAdd(a', b');
assert Suc(Add(a', b')) == Add(Suc(a'), b');}
Suc(Add(Add(Suc(a'), b'), Suc(c')));
== {SucAdd(Add(Suc(a'), b'), Suc(c'));
assert Suc(Add(Add(Suc(a'), b'), Suc(c'))) == Add(Suc(Add(Suc(a'), b')), Suc(c'));}
Add(Suc(Add(Suc(a'), b')), Suc(c'));
== // def. Add
Add(Add(Suc(a'), Suc(b')), Suc(c'));
==
Add(Add(a,b), c);
}
}
lemma AddCommutative(a: Unary, b: Unary)
ensures Add(a, b) == Add(b, a)
{
match b
case Zero =>
calc{
Add(a, b);
==
Add(a, Zero);
== // def. Add
a;
== {AddZero(a);
assert Add(Zero, a) == a;}
Add(Zero, a);
==
Add(b, a);
}
case Suc(b') =>
calc{
Add(a, b);
==
Add(a, Suc(b'));
== // def. Add
Suc(Add(a, b'));
== {AddCommutative(a, b');
assert Add(a, b') == Add(b', a);}
Suc(Add(b', a));
== {SucAdd(b', a);
assert Suc(Add(b',a)) == Add(Suc(b'),a);}
Add(Suc(b'), a);
==
Add(b, a);
}
}
method Main() {
var U3 := Suc(Suc(Suc(Zero)));
assert UnaryToNat(U3) == 3;
var U7 := Suc(Suc(Suc(Suc(U3))));
assert UnaryToNat(U7) == 7;
var d, m := IterativeDivMod(U7, U3);
assert Add(Mul(d, U3), m) == U7 && Less(m, U3);
print "Just as 7 divided by 3 is 2 with a remainder of 1, IterativeDivMod(", U7, ", ", U3, ") is ", d, " with a remainder of ", m;
}
|
AssertivePrograming_tmp_tmpwf43uz0e_DivMode_Unary.dfy
|
004
|
004
|
Dafny program: 004
|
// Noa Leron 207131871
// Tsuri Farhana 315016907
ghost predicate ExistsSubstring(str1: string, str2: string) {
// string in Dafny is a sequence of characters (seq<char>) and <= on sequences is the prefix relation
exists offset :: 0 <= offset <= |str1| && str2 <= str1[offset..]
}
ghost predicate Post(str1: string, str2: string, found: bool, i: nat) {
(found <==> ExistsSubstring(str1, str2)) &&
(found ==> i + |str2| <= |str1| && str2 <= str1[i..])
}
/*
Goal: Verify correctness of the following code. Once done, remove the {:verify false} (or turn it into {:verify true}).
Feel free to add GHOST code, including calls to lemmas. But DO NOT modify the specification or the original (executable) code.
*/
method {:verify true} FindFirstOccurrence(str1: string, str2: string) returns (found: bool, i: nat)
ensures Post(str1, str2, found, i)
{
if |str2| == 0 {
found, i := true, 0;
}
else if |str1| < |str2| {
found, i := false, 0; // value of i irrelevant in this case
}
else {
found, i := false, |str2|-1;
while !found && i < |str1|
{
var j := |str2|-1;
ghost var old_i := i;
ghost var old_j := j;
while !found && str1[i] == str2[j]
{
if j == 0 {
found := true;
}
else {
i, j := i-1, j-1;
}
}
if !found {
Lemma1(str1, str2, i, j, old_i, old_j, found); // ==>
i := i+|str2|-j;
}
}
}
}
method Main() {
var str1a, str1b := "string", " in Dafny is a sequence of characters (seq<char>)";
var str1, str2 := str1a + str1b, "ring";
var found, i := FindFirstOccurrence(str1, str2);
var offset := 2;
}
}
}
print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found;
if found {
print " and i == ", i;
}
str1 := "<= on sequences is the prefix relation";
found, i := FindFirstOccurrence(str1, str2);
print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found;
if found {
print " and i == ", i;
}
}
//this is our lemmas, invatiants and presicats
ghost predicate Outter_Inv_correctness(str1: string, str2: string, found: bool, i : nat)
{
(found ==> (i + |str2| <= |str1| && str2 <= str1[i..])) // Second part of post condition
&&
(!found && 0 < i <= |str1| && i != |str2|-1 ==> !(ExistsSubstring(str1[..i], str2))) // First part of post condition
&&
(!found ==> i <= |str1|)
}
ghost predicate Inner_Inv_correctness(str1: string, str2: string, i : nat, j: int, found: bool){
0 <= j <= i && // index in range
j < |str2| && // index in range
i < |str1| &&// index in range
(str1[i] == str2[j] ==> str2[j..] <= str1[i..]) &&
(found ==> j==0 && str1[i] == str2[j])
}
ghost predicate Inner_Inv_Termination(str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat){
old_j - j == old_i - i
}
lemma {:verify true} Lemma1 (str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat, found: bool)
// requires old_j - j == old_i - i;
requires !found;
requires |str2| > 0;
requires Outter_Inv_correctness(str1, str2, found, old_i);
requires i+|str2|-j == old_i + 1;
requires old_i+1 >= |str2|;
requires old_i+1 <= |str1|;
requires 0 <= i < |str1| && 0 <= j < |str2|;
requires str1[i] != str2[j];
requires |str2| > 0;
requires 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2));
ensures 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2));
{
calc{
0 < old_i+1 <= |str1|
&& (ExistsSubstring(str1[..old_i+1], str2))
&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);
==>
(!(ExistsSubstring(str1[..old_i], str2)))
&& (ExistsSubstring(str1[..old_i+1], str2))
&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);
==> {Lemma2(str1, str2, old_i, found);}
((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==>
(|str1[old_i+1 - |str2|..old_i+1]| == |str2|) && (str2 <= str1[old_i+1 - |str2| .. old_i+1]))
&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);
==>
((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> false);
}
}
lemma {:verify true} Lemma2 (str1: string, str2: string, i : nat, found: bool)
requires 0 <= i < |str1|;
requires 0 < |str2| <= i+1;
requires !ExistsSubstring(str1[..i], str2);
requires ExistsSubstring(str1[..i+1], str2);
ensures str2 <= str1[i+1 - |str2| .. i+1];
{
&& ((offset <= i) || (offset == i+1));
calc{
(0 < |str2|)
&& (!exists offset :: 0 <= offset <= i && str2 <= str1[offset..i])
&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);
==>
(0 < |str2|)
&& (forall offset :: 0 <= offset <= i ==> !(str2 <= str1[offset..i]))
&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1])
&& (forall offset :: 0 <= offset <= i+1 ==>
(offset <= i ==> !(str2 <= str1[offset..i])));
==> {Lemma3(str1, str2, i);}
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0) && (offset != i+1));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset <= i));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& !(str2 <= str1[offset..i]));
==>
str2 <= str1[i+1 - |str2| .. i+1];
}
}
lemma Lemma3(str1: string, str2: string, i : nat)
requires 0 <= i < |str1|;
requires 0 < |str2| <= i+1;
requires exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1];
requires forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]));
ensures exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i]));
{
var offset :| (0 <= offset <= i+1) && str2 <= str1[offset..i+1];
}
|
// Noa Leron 207131871
// Tsuri Farhana 315016907
ghost predicate ExistsSubstring(str1: string, str2: string) {
// string in Dafny is a sequence of characters (seq<char>) and <= on sequences is the prefix relation
exists offset :: 0 <= offset <= |str1| && str2 <= str1[offset..]
}
ghost predicate Post(str1: string, str2: string, found: bool, i: nat) {
(found <==> ExistsSubstring(str1, str2)) &&
(found ==> i + |str2| <= |str1| && str2 <= str1[i..])
}
/*
Goal: Verify correctness of the following code. Once done, remove the {:verify false} (or turn it into {:verify true}).
Feel free to add GHOST code, including calls to lemmas. But DO NOT modify the specification or the original (executable) code.
*/
method {:verify true} FindFirstOccurrence(str1: string, str2: string) returns (found: bool, i: nat)
ensures Post(str1, str2, found, i)
{
if |str2| == 0 {
found, i := true, 0;
assert Post(str1, str2, found, i); // this case is easy for dafny :)
}
else if |str1| < |str2| {
found, i := false, 0; // value of i irrelevant in this case
assert Post(str1, str2, found, i); // this case is easy for dafny :)
}
else {
found, i := false, |str2|-1;
assert |str2| > 0;
assert |str1| >= |str2|;
assert Outter_Inv_correctness(str1, str2, false, |str2|-1);
while !found && i < |str1|
invariant Outter_Inv_correctness(str1, str2, found, i);
decreases if !found then 1 else 0, |str1| - i;
{
assert Outter_Inv_correctness(str1, str2, found, i);
assert |str2| > 0;
assert !found && i < |str1|;
var j := |str2|-1;
ghost var old_i := i;
ghost var old_j := j;
while !found && str1[i] == str2[j]
invariant Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);
invariant Inner_Inv_correctness (str1, str2, i, j, found);
decreases j, if !found then 1 else 0;
{
if j == 0 {
assert j==0 && str1[i] == str2[j];
found := true;
assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);
assert Inner_Inv_correctness(str1, str2, i, j, found);
}
else {
assert j > 0;
assert Inner_Inv_Termination(str1, str2, i-1, j-1, old_i, old_j);
assert Inner_Inv_correctness(str1, str2, i-1, j-1, found);
i, j := i-1, j-1;
assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);
assert Inner_Inv_correctness(str1, str2, i, j, found);
}
assert j >= 0;
assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);
assert Inner_Inv_correctness(str1, str2, i, j, found);
}
assert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);
assert Inner_Inv_correctness(str1, str2, i, j, found);
assert found || str1[i] != str2[j]; // gaurd negation
assert found ==> i + |str2| <= |str1| && str2 <= str1[i..];
assert !found ==> str1[i] != str2[j];
if !found {
assert i < |str1|;
assert |str2| > 0;
assert old_j - j == old_i - i;
assert old_i < i+|str2|-j;
assert Outter_Inv_correctness(str1, str2, found, old_i);
assert i+|str2|-j == old_i + 1;
assert str1[i] != str2[j];
assert |str1[old_i+1 - |str2|..old_i+1]| == |str2|;
assert str1[old_i+1 - |str2|..old_i+1] != str2;
assert 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2));
Lemma1(str1, str2, i, j, old_i, old_j, found); // ==>
assert 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2));
assert 0 < i+|str2|-j <= |str1| ==> !(ExistsSubstring(str1[..i+|str2|-j], str2));
assert Outter_Inv_correctness(str1, str2, found, i+|str2|-j);
i := i+|str2|-j;
assert old_i < i;
assert Outter_Inv_correctness(str1, str2, found, i);
assert i <= |str1|;
}
assert !found ==> i <= |str1|;
assert !found ==> old_i < i;
assert !found ==> Outter_Inv_correctness(str1, str2, found, i);
assert found ==> Outter_Inv_correctness(str1, str2, found, i);
assert Outter_Inv_correctness(str1, str2, found, i);
}
assert Outter_Inv_correctness(str1, str2, found, i);
assert (found ==> i + |str2| <= |str1| && str2 <= str1[i..]);
assert (!found && 0 < i <= |str1| ==> !(ExistsSubstring(str1[..i], str2)));
assert (!found ==> i <= |str1|);
assert found || i >= |str1|; // gaurd negation
assert (!found && i == |str1| ==> !(ExistsSubstring(str1[..i], str2)));
assert i == |str1| ==> str1[..i] == str1;
assert (!found && i == |str1| ==> !(ExistsSubstring(str1, str2)));
assert !found ==> i >= |str1|;
assert !found ==> i == |str1|;
assert (!found ==> !ExistsSubstring(str1, str2));
assert (found ==> ExistsSubstring(str1, str2));
assert (found <==> ExistsSubstring(str1, str2));
assert (found ==> i + |str2| <= |str1| && str2 <= str1[i..]);
assert Post(str1, str2, found, i);
}
assert Post(str1, str2, found, i);
}
method Main() {
var str1a, str1b := "string", " in Dafny is a sequence of characters (seq<char>)";
var str1, str2 := str1a + str1b, "ring";
var found, i := FindFirstOccurrence(str1, str2);
assert found by {
assert ExistsSubstring(str1, str2) by {
var offset := 2;
assert 0 <= offset <= |str1|;
assert str2 <= str1[offset..] by {
assert str2 == str1[offset..][..4];
}
}
}
print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found;
if found {
print " and i == ", i;
}
str1 := "<= on sequences is the prefix relation";
found, i := FindFirstOccurrence(str1, str2);
print "\nfound, i := FindFirstOccurrence(\"", str1, "\", \"", str2, "\") returns found == ", found;
if found {
print " and i == ", i;
}
}
//this is our lemmas, invatiants and presicats
ghost predicate Outter_Inv_correctness(str1: string, str2: string, found: bool, i : nat)
{
(found ==> (i + |str2| <= |str1| && str2 <= str1[i..])) // Second part of post condition
&&
(!found && 0 < i <= |str1| && i != |str2|-1 ==> !(ExistsSubstring(str1[..i], str2))) // First part of post condition
&&
(!found ==> i <= |str1|)
}
ghost predicate Inner_Inv_correctness(str1: string, str2: string, i : nat, j: int, found: bool){
0 <= j <= i && // index in range
j < |str2| && // index in range
i < |str1| &&// index in range
(str1[i] == str2[j] ==> str2[j..] <= str1[i..]) &&
(found ==> j==0 && str1[i] == str2[j])
}
ghost predicate Inner_Inv_Termination(str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat){
old_j - j == old_i - i
}
lemma {:verify true} Lemma1 (str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat, found: bool)
// requires old_j - j == old_i - i;
requires !found;
requires |str2| > 0;
requires Outter_Inv_correctness(str1, str2, found, old_i);
requires i+|str2|-j == old_i + 1;
requires old_i+1 >= |str2|;
requires old_i+1 <= |str1|;
requires 0 <= i < |str1| && 0 <= j < |str2|;
requires str1[i] != str2[j];
requires |str2| > 0;
requires 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2));
ensures 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2));
{
assert |str1[old_i+1 - |str2|..old_i+1]| == |str2|;
assert str1[old_i+1 - |str2|..old_i+1] != str2;
assert !(str2 <= str1[old_i+1 - |str2|..old_i+1]);
assert 0 <= old_i < old_i+1 <= |str1|;
assert old_i+1 >= |str2|;
calc{
0 < old_i+1 <= |str1|
&& (ExistsSubstring(str1[..old_i+1], str2))
&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);
==>
(!(ExistsSubstring(str1[..old_i], str2)))
&& (ExistsSubstring(str1[..old_i+1], str2))
&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);
==> {Lemma2(str1, str2, old_i, found);}
((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==>
(|str1[old_i+1 - |str2|..old_i+1]| == |str2|) && (str2 <= str1[old_i+1 - |str2| .. old_i+1]))
&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);
==>
((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> false);
}
}
lemma {:verify true} Lemma2 (str1: string, str2: string, i : nat, found: bool)
requires 0 <= i < |str1|;
requires 0 < |str2| <= i+1;
requires !ExistsSubstring(str1[..i], str2);
requires ExistsSubstring(str1[..i+1], str2);
ensures str2 <= str1[i+1 - |str2| .. i+1];
{
assert exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]
&& ((offset <= i) || (offset == i+1));
calc{
(0 < |str2|)
&& (!exists offset :: 0 <= offset <= i && str2 <= str1[offset..i])
&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);
==>
(0 < |str2|)
&& (forall offset :: 0 <= offset <= i ==> !(str2 <= str1[offset..i]))
&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1])
&& (forall offset :: 0 <= offset <= i+1 ==>
(offset <= i ==> !(str2 <= str1[offset..i])));
==> {Lemma3(str1, str2, i);}
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0) && (offset != i+1));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset <= i));
==>
(0 < |str2|)
&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1])
&& !(str2 <= str1[offset..i]));
==>
str2 <= str1[i+1 - |str2| .. i+1];
}
}
lemma Lemma3(str1: string, str2: string, i : nat)
requires 0 <= i < |str1|;
requires 0 < |str2| <= i+1;
requires exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1];
requires forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]));
ensures exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i]));
{
var offset :| (0 <= offset <= i+1) && str2 <= str1[offset..i+1];
assert 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]));
}
|
AssertivePrograming_tmp_tmpwf43uz0e_Find_Substring.dfy
|
005
|
005
|
Dafny program: 005
|
// Noa Leron 207131871
// Tsuri Farhana 315016907
predicate Sorted(q: seq<int>) {
forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]
}
/*
Goal: Implement the well known merge sort algorithm in O(a.Length X log_2(a.Length)) time, recursively.
- Divide the contents of the original array into two local arrays
- After sorting the local arrays (recursively), merge the contents of the two returned arrays using the Merge method (see below)
- DO NOT modify the specification or any other part of the method's signature
- DO NOT introduce any further methods
*/
method MergeSort(a: array<int>) returns (b: array<int>)
ensures b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..])
{
if (a.Length <= 1) {b := a;}
else{
var mid: nat := a.Length / 2;
var a1: array<int> := new int[mid];
var a2: array<int> := new int[a.Length - mid];
var i: nat := 0;
while (i < a1.Length )
{
a1[i] := a[i];
a2[i] := a[i+mid];
i:=i+1;
}
if(a1.Length < a2.Length) {
a2[i] := a[i+mid];
} // If a.Length is odd.
else{
}
a1:= MergeSort(a1);
a2:= MergeSort(a2);
b := new int [a.Length];
Merge(b, a1, a2);
}
}
ghost predicate Inv(a: seq<int>, a1: seq<int>, a2: seq<int>, i: nat, mid: nat){
(i <= |a1|) && (i <= |a2|) && (i+mid <= |a|) &&
(a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)])
}
/*
Goal: Implement iteratively, correctly, efficiently, clearly
DO NOT modify the specification or any other part of the method's signature
*/
method Merge(b: array<int>, c: array<int>, d: array<int>)
requires b != c && b != d && b.Length == c.Length + d.Length
requires Sorted(c[..]) && Sorted(d[..])
ensures Sorted(b[..]) && multiset(b[..]) == multiset(c[..])+multiset(d[..])
modifies b
{
var i: nat, j: nat := 0, 0;
while i + j < b.Length
{
i,j := MergeLoop (b,c,d,i,j);
}
LemmaMultysetsEquals(b[..],c[..],d[..],i,j);
}
//This is a method that replace the loop body
method {:verify true} MergeLoop(b: array<int>, c: array<int>, d: array<int>,i0: nat , j0: nat) returns (i: nat, j: nat)
requires b != c && b != d && b.Length == c.Length + d.Length
requires Sorted(c[..]) && Sorted(d[..])
requires i0 <= c.Length && j0 <= d.Length && i0 + j0 <= b.Length
requires InvSubSet(b[..],c[..],d[..],i0,j0)
requires InvSorted(b[..],c[..],d[..],i0,j0)
requires i0 + j0 < b.Length
modifies b
ensures i <= c.Length && j <= d.Length && i + j <= b.Length
ensures InvSubSet(b[..],c[..],d[..],i,j)
ensures InvSorted(b[..],c[..],d[..],i,j)
//decreases ensures
ensures 0 <= c.Length - i < c.Length - i0 || (c.Length - i == c.Length - i0 && 0 <= d.Length - j < d.Length - j0)
{
i,j := i0,j0;
if(i == c.Length || (j< d.Length && d[j] < c[i])){
// in this case we take the next value from d
b[i+j] := d[j];
lemmaInvSubsetTakeValueFromD(b[..],c[..],d[..],i,j);
j := j + 1;
}
else{
// in this case we take the next value from c
b[i+j] := c[i];
lemmaInvSubsetTakeValueFromC(b[..],c[..],d[..],i,j);
i := i + 1;
}
}
//Loop invariant - b is sprted so far and the next two potential values that will go into b are bigger then the biggest value in b.
ghost predicate InvSorted(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){
i <= |c| && j <= |d| && i + j <= |b| &&
((i+j > 0 && i < |c|) ==> (b[j + i - 1] <= c[i])) &&
((i+j > 0 && j < |d|) ==> (b[j + i - 1] <= d[j])) &&
Sorted(b[..i+j])
}
//Loop invariant - the multiset of the prefix of b so far is the same multiset as the prefixes of c and d so far.
ghost predicate InvSubSet(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){
i <= |c| && j <= |d| && i + j <= |b| &&
multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
}
//This lemma helps dafny see that if the prefixs of arrays are the same multiset until the end of the arrays,
//all the arrays are the same multiset.
lemma LemmaMultysetsEquals (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat)
requires i == |c|;
requires j == |d|;
requires i + j == |b|;
requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
ensures multiset(b[..]) == multiset(c[..])+multiset(d[..]);
{
}
//This lemma helps dafny see that after adding the next value from c to b the prefixes are still the same subsets.
lemma lemmaInvSubsetTakeValueFromC (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat)
requires i < |c|;
requires j <= |d|;
requires i + j < |b|;
requires |c| + |d| == |b|;
requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
requires b[i+j] == c[i]
ensures multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j])
{
}
//This lemma helps dafny see that after adding the next value from d to b the prefixes are still the same subsets.
lemma{:verify true} lemmaInvSubsetTakeValueFromD (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat)
requires i <= |c|;
requires j < |d|;
requires i + j < |b|;
requires |c| + |d| == |b|;
requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
requires b[i+j] == d[j]
ensures multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1])
{
}
method Main() {
var a := new int[3] [4, 8, 6];
var q0 := a[..];
a := MergeSort(a);
print "\nThe sorted version of ", q0, " is ", a[..];
a := new int[5] [3, 8, 5, -1, 10];
q0 := a[..];
a := MergeSort(a);
print "\nThe sorted version of ", q0, " is ", a[..];
//assert a[..] == [-1, 3, 5, 8, 10];
}
|
// Noa Leron 207131871
// Tsuri Farhana 315016907
predicate Sorted(q: seq<int>) {
forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]
}
/*
Goal: Implement the well known merge sort algorithm in O(a.Length X log_2(a.Length)) time, recursively.
- Divide the contents of the original array into two local arrays
- After sorting the local arrays (recursively), merge the contents of the two returned arrays using the Merge method (see below)
- DO NOT modify the specification or any other part of the method's signature
- DO NOT introduce any further methods
*/
method MergeSort(a: array<int>) returns (b: array<int>)
ensures b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..])
decreases a.Length
{
if (a.Length <= 1) {b := a;}
else{
var mid: nat := a.Length / 2;
var a1: array<int> := new int[mid];
var a2: array<int> := new int[a.Length - mid];
assert a1.Length <= a2.Length;
assert a.Length == a1.Length + a2.Length;
var i: nat := 0;
while (i < a1.Length )
invariant Inv(a[..], a1[..], a2[..], i, mid)
decreases a1.Length - i
{
a1[i] := a[i];
a2[i] := a[i+mid];
i:=i+1;
}
assert !(i < a1.Length);
assert (i >= a1.Length);
assert i == a1.Length;
assert Inv(a[..], a1[..], a2[..], i, mid);
assert (i <= |a1[..]|) && (i <= |a2[..]|) && (i+mid <= |a[..]|);
assert (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]);
if(a1.Length < a2.Length) {
a2[i] := a[i+mid];
assert i+1 == a2.Length;
assert (a2[..i+1] == a[mid..(i+1+mid)]);
assert (a1[..i] == a[..i]) && (a2[..i+1] == a[mid..(i+1+mid)]);
assert a[..i] + a[i..i+1+mid] == a1[..i] + a2[..i+1];
assert a[..i] + a[i..i+1+mid] == a1[..] + a2[..];
assert a[..] == a1[..] + a2[..];
} // If a.Length is odd.
else{
assert i == a2.Length;
assert (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]);
assert a[..i] + a[i..i+mid] == a1[..i] + a2[..i];
assert a[..i] + a[i..i+mid] == a1[..] + a2[..];
assert a[..] == a1[..] + a2[..];
}
assert a1.Length < a.Length;
a1:= MergeSort(a1);
assert a2.Length < a.Length;
a2:= MergeSort(a2);
b := new int [a.Length];
Merge(b, a1, a2);
assert multiset(b[..]) == multiset(a1[..]) + multiset(a2[..]);
assert Sorted(b[..]);
}
assert b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..]);
}
ghost predicate Inv(a: seq<int>, a1: seq<int>, a2: seq<int>, i: nat, mid: nat){
(i <= |a1|) && (i <= |a2|) && (i+mid <= |a|) &&
(a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)])
}
/*
Goal: Implement iteratively, correctly, efficiently, clearly
DO NOT modify the specification or any other part of the method's signature
*/
method Merge(b: array<int>, c: array<int>, d: array<int>)
requires b != c && b != d && b.Length == c.Length + d.Length
requires Sorted(c[..]) && Sorted(d[..])
ensures Sorted(b[..]) && multiset(b[..]) == multiset(c[..])+multiset(d[..])
modifies b
{
var i: nat, j: nat := 0, 0;
while i + j < b.Length
invariant i <= c.Length && j <= d.Length && i + j <= b.Length
invariant InvSubSet(b[..],c[..],d[..],i,j)
invariant InvSorted(b[..],c[..],d[..],i,j)
decreases c.Length-i, d.Length-j
{
i,j := MergeLoop (b,c,d,i,j);
assert InvSubSet(b[..],c[..],d[..],i,j);
assert InvSorted(b[..],c[..],d[..],i,j);
}
assert InvSubSet(b[..],c[..],d[..],i,j);
LemmaMultysetsEquals(b[..],c[..],d[..],i,j);
assert multiset(b[..]) == multiset(c[..])+multiset(d[..]);
}
//This is a method that replace the loop body
method {:verify true} MergeLoop(b: array<int>, c: array<int>, d: array<int>,i0: nat , j0: nat) returns (i: nat, j: nat)
requires b != c && b != d && b.Length == c.Length + d.Length
requires Sorted(c[..]) && Sorted(d[..])
requires i0 <= c.Length && j0 <= d.Length && i0 + j0 <= b.Length
requires InvSubSet(b[..],c[..],d[..],i0,j0)
requires InvSorted(b[..],c[..],d[..],i0,j0)
requires i0 + j0 < b.Length
modifies b
ensures i <= c.Length && j <= d.Length && i + j <= b.Length
ensures InvSubSet(b[..],c[..],d[..],i,j)
ensures InvSorted(b[..],c[..],d[..],i,j)
//decreases ensures
ensures 0 <= c.Length - i < c.Length - i0 || (c.Length - i == c.Length - i0 && 0 <= d.Length - j < d.Length - j0)
{
i,j := i0,j0;
if(i == c.Length || (j< d.Length && d[j] < c[i])){
// in this case we take the next value from d
assert InvSorted(b[..][i+j:=d[j]],c[..],d[..],i,j+1);
b[i+j] := d[j];
lemmaInvSubsetTakeValueFromD(b[..],c[..],d[..],i,j);
assert InvSubSet(b[..],c[..],d[..],i,j+1);
assert InvSorted(b[..],c[..],d[..],i,j+1);
j := j + 1;
}
else{
assert j == d.Length || (i < c.Length && c[i] <= d[j]);
// in this case we take the next value from c
assert InvSorted(b[..][i+j:=c[i]],c[..],d[..],i+1,j);
b[i+j] := c[i];
lemmaInvSubsetTakeValueFromC(b[..],c[..],d[..],i,j);
assert InvSubSet(b[..],c[..],d[..],i+1,j);
assert InvSorted(b[..],c[..],d[..],i+1,j);
i := i + 1;
}
}
//Loop invariant - b is sprted so far and the next two potential values that will go into b are bigger then the biggest value in b.
ghost predicate InvSorted(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){
i <= |c| && j <= |d| && i + j <= |b| &&
((i+j > 0 && i < |c|) ==> (b[j + i - 1] <= c[i])) &&
((i+j > 0 && j < |d|) ==> (b[j + i - 1] <= d[j])) &&
Sorted(b[..i+j])
}
//Loop invariant - the multiset of the prefix of b so far is the same multiset as the prefixes of c and d so far.
ghost predicate InvSubSet(b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat){
i <= |c| && j <= |d| && i + j <= |b| &&
multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
}
//This lemma helps dafny see that if the prefixs of arrays are the same multiset until the end of the arrays,
//all the arrays are the same multiset.
lemma LemmaMultysetsEquals (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat)
requires i == |c|;
requires j == |d|;
requires i + j == |b|;
requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
ensures multiset(b[..]) == multiset(c[..])+multiset(d[..]);
{
assert b[..] == b[..i+j];
assert c[..] == c[..i];
assert d[..] == d[..j];
}
//This lemma helps dafny see that after adding the next value from c to b the prefixes are still the same subsets.
lemma lemmaInvSubsetTakeValueFromC (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat)
requires i < |c|;
requires j <= |d|;
requires i + j < |b|;
requires |c| + |d| == |b|;
requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
requires b[i+j] == c[i]
ensures multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j])
{
assert c[..i]+[c[i]] == c[..i+1];
assert b[..i+j+1] == b[..i+j] + [b[i+j]];
assert multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j]);
}
//This lemma helps dafny see that after adding the next value from d to b the prefixes are still the same subsets.
lemma{:verify true} lemmaInvSubsetTakeValueFromD (b: seq<int>, c: seq<int>, d: seq<int>, i: nat, j: nat)
requires i <= |c|;
requires j < |d|;
requires i + j < |b|;
requires |c| + |d| == |b|;
requires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])
requires b[i+j] == d[j]
ensures multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1])
{
assert d[..j]+[d[j]] == d[..j+1];
assert b[..i+j+1] == b[..i+j] + [b[i+j]];
assert multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1]);
}
method Main() {
var a := new int[3] [4, 8, 6];
var q0 := a[..];
assert q0 == [4,8,6];
a := MergeSort(a);
assert a.Length == |q0| && multiset(a[..]) == multiset(q0);
print "\nThe sorted version of ", q0, " is ", a[..];
assert Sorted(a[..]);
assert a[..] == [4, 6, 8];
a := new int[5] [3, 8, 5, -1, 10];
q0 := a[..];
assert q0 == [3, 8, 5, -1, 10];
a := MergeSort(a);
assert a.Length == |q0| && multiset(a[..]) == multiset(q0);
print "\nThe sorted version of ", q0, " is ", a[..];
assert Sorted(a[..]);
//assert a[..] == [-1, 3, 5, 8, 10];
}
|
AssertivePrograming_tmp_tmpwf43uz0e_MergeSort.dfy
|
006
|
006
|
Dafny program: 006
|
// method CountLessThan(numbers: set<int>, threshold: int) returns (count: int)
// // ensures count == |set i | i in numbers && i < threshold|
// ensures count == |SetLessThan(numbers, threshold)|
// {
// count := 0;
// var ss := numbers;
// while ss != {}
// decreases |ss|
// {
// var i: int :| i in ss;
// ss := ss - {i};
// if i < threshold {
// count := count + 1;
// }
// }
// assert count == |SetLessThan(numbers, threshold)|;
// // assert count == |set i | i in numbers && i < threshold|;
// }
function SetLessThan(numbers: set<int>, threshold: int): set<int>
{
set i | i in numbers && i < threshold
}
method Main()
{
// var s: set<int> := {1, 2, 3, 4, 5};
// var c: int := CountLessThan(s, 4);
// print c;
// assert c == 3;
// if you manualy create set and sequence with same elements, |s|==|t| works
var t: seq<int> := [1, 2, 3];
var s: set<int> := {1, 2, 3};
// but if you create set from the sequence with distinct elements it does not understand that |s|==|t|
// Dafny has problems when reasoning about set sizes ==>
s := set x | x in t;
// assert |s| == |t|; // not verifying
// assert |s| == 3; // not verifying
// other expriments
set_memebrship_implies_cardinality(s, set x | x in t); // s and the other argument is the same thing
var s2 : set<int> := set x | x in t;
s2 := {1, 2, 3};
// assert |s| == |s2|; // may not hold
set_memebrship_implies_cardinality(s, s2);
}
lemma set_memebrship_implies_cardinality_helper<A>(s: set<A>, t: set<A>, s_size: int)
requires s_size >= 0 && s_size == |s|
requires forall x :: x in s <==> x in t
ensures |s| == |t|
if s_size == 0 {
} else {
var s_hd;
// assign s_hd to a value *such that* s_hd is in s (see such_that expressions)
s_hd :| s_hd in s;
set_memebrship_implies_cardinality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);
}
}
lemma set_memebrship_implies_cardinality<A>(s: set<A>, t: set<A>)
requires forall x :: x in s <==> x in t
ensures |s| == |t| {
set_memebrship_implies_cardinality_helper(s, t, |s|);
}
/*
lemma Bijection(arr: seq<int>, s: set<int>) // returns (bool)
requires sorted(arr)
// requires forall x, y :: x in s && y in s && x != y ==> x < y
ensures |s| == |arr|
{
var mapping: map<int, int> := map[];
// Establish the bijection
for i := 0 to |arr| {
mapping := mapping[arr[i]:= arr[i]];
}
// Prove injectiveness
// Prove surjectiveness
// assert forall x :: x in s ==> exists i :: 0 <= i < |arr|-1 && arr[i] == x;
// Conclude equinumerosity
// assert |s| == |arr|;
// return true;
}
*/
function seqSet(nums: seq<int>, index: nat): set<int> {
set x | 0 <= x < index < |nums| :: nums[x]
}
lemma containsDuplicateI(nums: seq<int>) returns (containsDuplicate: bool)
ensures containsDuplicate ==> exists i,j :: 0 <= i < j < |nums| && nums[i] == nums[j]
{
var windowGhost: set<int> := {};
var windowSet: set<int> := {};
for i:= 0 to |nums|
// invariant forall x :: x in windowSet ==> x in nums
{
windowGhost := windowSet;
if nums[i] in windowSet { // does not verify
// if nums[i] in seqSet(nums, i) { //verifies
return true;
}
windowSet := windowSet + {nums[i]};
}
return false;
}
// lemma numElemsOfSet(a: seq<int>)
// requires sorted(a)
// {
// assert distinct(a);
// var s := set x | x in a;
// assert forall x :: x in s ==> x in a[..];
// assert forall x :: x in a ==> x in s;
// assert |s| == |a|;
// }
// lemma CardinalitySetEqualsArray(a: seq<int>, s: set<int>)
// requires s == set x | x in a
// requires distinct(a)
// ensures |s| == |a|
// {
// assert forall x :: x in s ==> exists i :: 0 <= i < |a| && a[i] == x;
// assert forall i, j :: 0 <= i < |a| && 0 <= j < |a| && i != j ==> a[i] != a[j];
// // Assert that each element in the array is in the set
// assert forall i :: 0 <= i < |a| ==> a[i] in s;
// // Assert that the set contains exactly the elements in the array
// assert s == set x | x in a;
// // Assert that the set is a subset of the array
// assert forall x :: x in s <==> x in a;
// // Conclude the equivalence
// assert |s| == |a|;
// }
/*
lemma memebrship_implies_cardinality_helper<A>(s: set<A>, t: seq<A>, s_size: int)
requires s_size >= 0 && s_size == |s|
requires forall x :: x in s <==> x in t
requires forall i, j :: (0 <= i < |t| && 0 <= j < |t| && i != j ) ==> t[i] != t[j]
requires |set x | x in t| == |t|
ensures |s| == |t|
if s_size == 0 {
} else {
var t_hd;
t_hd := t[0];
ghost var t_h := set x | x in t[1..];
memebrship_implies_cardinality_helper(s - {t_hd}, t[1..], s_size - 1);
}
}
lemma memebrship_implies_cardinality<A>(s: set<A>, t: seq<A>)
requires forall x :: x in s <==> x in t
ensures |s| == |t| {
memebrship_implies_cardinality_helper(s, t, |s|);
}
*/
lemma set_memebrship_implies_equality_helper<A>(s: set<A>, t: set<A>, s_size: int)
requires s_size >= 0 && s_size == |s|
requires forall x :: x in s <==> x in t
ensures s == t
if s_size == 0 {
} else {
var s_hd;
// assign s_hd to a value *such that* s_hd is in s (see such_that expressions)
s_hd :| s_hd in s;
set_memebrship_implies_equality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);
}
}
lemma set_memebrship_implies_equality<A>(s: set<A>, t: set<A>)
requires forall x :: x in s <==> x in t
ensures s == t {
set_memebrship_implies_equality_helper(s, t, |s|);
}
// TODO play with this for keys==Contents
lemma set_seq_equality(s: set<int>, t: seq<int>)
requires distinct(t)
requires forall x :: x in t <==> x in s
{
var s2 : set<int> := set x | x in t;
set_memebrship_implies_equality_helper(s, s2, |s|);
// assert |s2| == |t|;
// assert |s| == |t|;
}
ghost predicate SortedSeq(a: seq<int>)
//sequence is sorted from left to right
{
(forall i,j :: 0<= i< j < |a| ==> ( a[i] < a[j] ))
}
method GetInsertIndex(a: array<int>, limit: int, x:int) returns (idx:int)
// get index so that array stays sorted
requires x !in a[..]
requires 0 <= limit <= a.Length
requires SortedSeq(a[..limit])
ensures 0<= idx <= limit
ensures SortedSeq(a[..limit])
ensures idx > 0 ==> a[idx-1]< x
ensures idx < limit ==> x < a[idx]
{
idx := limit;
for i := 0 to limit
{
if x < a[i] {
idx := i;
break;
}
}
}
predicate sorted(a: seq<int>)
{
forall i,j :: 0 <= i < j < |a| ==> a[i] < a[j]
}
predicate distinct(a: seq<int>)
{
forall i,j :: (0 <= i < |a| && 0 <= j < |a| && i != j) ==> a[i] != a[j]
}
predicate sorted_eq(a: seq<int>)
{
forall i,j :: 0 <= i < j < |a| ==> a[i] <= a[j]
}
predicate lessThan(a:seq<int>, key:int) {
forall i :: 0 <= i < |a| ==> a[i] < key
}
predicate greaterThan(a:seq<int>, key:int) {
forall i :: 0 <= i < |a| ==> a[i] > key
}
predicate greaterEqualThan(a:seq<int>, key:int) {
forall i :: 0 <= i < |a| ==> a[i] >= key
}
/*
method InsertSorted(a: array<int>, key: int ) returns (b: array<int>)
requires sorted_eq(a[..])
ensures sorted_eq(b[..])
{
b:= new int[a.Length + 1];
ghost var k := 0;
b[0] := key;
ghost var a' := a[..];
var i:= 0;
while (i < a.Length)
modifies b
{
if(a[i]<key)
{
b[i]:= a[i];
b[i+1] := key;
k := i+1;
}
else if (a[i] >= key)
{
b[i+1] := a[i];
}
i := i+1;
}
}
*/
lemma DistributiveLemma(a: seq<bool>, b: seq<bool>)
ensures count(a + b) == count(a) + count(b)
{
if a == [] {
} else {
DistributiveLemma(a[1..], b);
}
}
function count(a: seq<bool>): nat
{
if |a| == 0 then 0 else
(if a[0] then 1 else 0) + count(a[1..])
}
lemma DistributiveIn(a: seq<int>, b:seq<int>, k:int, key:int)
requires |a| + 1 == |b|
requires 0 <= k <= |a|
requires b == a[..k] + [key] + a[k..]
ensures forall i :: 0 <= i < |a| ==> a[i] in b
{
}
lemma DistributiveGreater(a: seq<int>, b:seq<int>, k:int, key:int)
requires |a| + 1 == |b|
requires 0 <= k <= |a|
requires b == a[..k] + [key] + a[k..]
requires forall j :: 0 <= j < |a| ==> a[j] > 0
requires key > 0
ensures forall i :: 0 <= i < |b| ==> b[i] > 0
{
// assert ((forall j :: 0 <= j < k ==> b[j] > 0) && (forall j :: k <= j < |a| ==> b[j] > 0)) ==> (forall j :: 0 <= j < |b| ==> b[j] > 0);
}
// verifies in more than 45 seconds, but less than 100 seconds
method InsertIntoSorted(a: array<int>, limit:int, key:int) returns (b: array<int>)
requires key > 0
requires key !in a[..]
requires 0 <= limit < a.Length
requires forall i :: 0 <= i < limit ==> a[i] > 0
requires forall i :: limit <= i < a.Length ==> a[i] == 0
requires sorted(a[..limit])
ensures b.Length == a.Length
ensures sorted(b[..(limit+ 1)])
ensures forall i :: limit + 1 <= i < b.Length ==> b[i] == 0
ensures forall i :: 0 <= i < limit ==> a[i] in b[..]
ensures forall i :: 0 <= i < limit + 1 ==> b[i] > 0
{
b:= new int[a.Length];
ghost var k := 0;
b[0] := key;
ghost var a' := a[..];
var i:= 0;
while (i < limit)
modifies b
{
if(a[i]<key)
{
b[i]:= a[i];
b[i+1] := key;
k := i+1;
}
else if (a[i] >= key)
{
b[i+1] := a[i];
}
i := i+1;
}
// assert b[..limit+1] == a[..k] + [key] + a[k..limit];
DistributiveIn(a[..limit], b[..limit+1], k, key);
DistributiveGreater(a[..limit], b[..limit+1], k, key);
// assert forall i :: 0 <= i < limit + 1 ==> b[i] > 0;
ghost var b' := b[..];
i := limit + 1;
while i < b.Length
{
b[i] := 0;
i := i + 1;
}
}
|
// method CountLessThan(numbers: set<int>, threshold: int) returns (count: int)
// // ensures count == |set i | i in numbers && i < threshold|
// ensures count == |SetLessThan(numbers, threshold)|
// {
// count := 0;
// var ss := numbers;
// while ss != {}
// decreases |ss|
// {
// var i: int :| i in ss;
// ss := ss - {i};
// if i < threshold {
// count := count + 1;
// }
// }
// assert count == |SetLessThan(numbers, threshold)|;
// // assert count == |set i | i in numbers && i < threshold|;
// }
function SetLessThan(numbers: set<int>, threshold: int): set<int>
{
set i | i in numbers && i < threshold
}
method Main()
{
// var s: set<int> := {1, 2, 3, 4, 5};
// var c: int := CountLessThan(s, 4);
// print c;
// assert c == 3;
// if you manualy create set and sequence with same elements, |s|==|t| works
var t: seq<int> := [1, 2, 3];
var s: set<int> := {1, 2, 3};
assert |s| == 3;
assert |s| == |t|;
// but if you create set from the sequence with distinct elements it does not understand that |s|==|t|
// Dafny has problems when reasoning about set sizes ==>
s := set x | x in t;
assert forall x :: x in t ==> x in s;
assert forall x :: x in s ==> x in t;
assert forall x :: x in s <==> x in t;
assert forall i, j :: 0 <= i < |t| && 0 <= j < |t| && i !=j ==> t[i] != t[j];
assert |t| == 3;
// assert |s| == |t|; // not verifying
// assert |s| == 3; // not verifying
// other expriments
set_memebrship_implies_cardinality(s, set x | x in t); // s and the other argument is the same thing
var s2 : set<int> := set x | x in t;
assert |s| == |s2|;
s2 := {1, 2, 3};
// assert |s| == |s2|; // may not hold
set_memebrship_implies_cardinality(s, s2);
assert |s| == |s2|; // after lemma it holds
}
lemma set_memebrship_implies_cardinality_helper<A>(s: set<A>, t: set<A>, s_size: int)
requires s_size >= 0 && s_size == |s|
requires forall x :: x in s <==> x in t
ensures |s| == |t|
decreases s_size {
if s_size == 0 {
} else {
var s_hd;
// assign s_hd to a value *such that* s_hd is in s (see such_that expressions)
s_hd :| s_hd in s;
set_memebrship_implies_cardinality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);
}
}
lemma set_memebrship_implies_cardinality<A>(s: set<A>, t: set<A>)
requires forall x :: x in s <==> x in t
ensures |s| == |t| {
set_memebrship_implies_cardinality_helper(s, t, |s|);
}
/*
lemma Bijection(arr: seq<int>, s: set<int>) // returns (bool)
requires sorted(arr)
// requires forall x, y :: x in s && y in s && x != y ==> x < y
ensures |s| == |arr|
{
var mapping: map<int, int> := map[];
// Establish the bijection
for i := 0 to |arr| {
mapping := mapping[arr[i]:= arr[i]];
}
// Prove injectiveness
assert forall i, j :: (0 <= i < |arr|-1 && 0 <= j < |arr|-1 && i != j )==> mapping[arr[i]] != mapping[arr[j]];
// Prove surjectiveness
// assert forall x :: x in s ==> exists i :: 0 <= i < |arr|-1 && arr[i] == x;
// Conclude equinumerosity
// assert |s| == |arr|;
// return true;
}
*/
function seqSet(nums: seq<int>, index: nat): set<int> {
set x | 0 <= x < index < |nums| :: nums[x]
}
lemma containsDuplicateI(nums: seq<int>) returns (containsDuplicate: bool)
ensures containsDuplicate ==> exists i,j :: 0 <= i < j < |nums| && nums[i] == nums[j]
{
var windowGhost: set<int> := {};
var windowSet: set<int> := {};
for i:= 0 to |nums|
invariant 0 <= i <= |nums|
invariant forall j :: 0 <= j < i < |nums| ==> nums[j] in windowSet
// invariant forall x :: x in windowSet ==> x in nums
invariant forall x :: x in windowSet ==> x in nums[0..i]
invariant seqSet(nums, i) <= windowSet
{
windowGhost := windowSet;
if nums[i] in windowSet { // does not verify
// if nums[i] in seqSet(nums, i) { //verifies
return true;
}
windowSet := windowSet + {nums[i]};
}
return false;
}
// lemma numElemsOfSet(a: seq<int>)
// requires sorted(a)
// {
// assert distinct(a);
// var s := set x | x in a;
// assert forall x :: x in s ==> x in a[..];
// assert forall x :: x in a ==> x in s;
// assert |s| == |a|;
// }
// lemma CardinalitySetEqualsArray(a: seq<int>, s: set<int>)
// requires s == set x | x in a
// requires distinct(a)
// ensures |s| == |a|
// {
// assert forall x :: x in s ==> exists i :: 0 <= i < |a| && a[i] == x;
// assert forall i, j :: 0 <= i < |a| && 0 <= j < |a| && i != j ==> a[i] != a[j];
// // Assert that each element in the array is in the set
// assert forall i :: 0 <= i < |a| ==> a[i] in s;
// // Assert that the set contains exactly the elements in the array
// assert s == set x | x in a;
// // Assert that the set is a subset of the array
// assert forall x :: x in s <==> x in a;
// // Conclude the equivalence
// assert |s| == |a|;
// }
/*
lemma memebrship_implies_cardinality_helper<A>(s: set<A>, t: seq<A>, s_size: int)
requires s_size >= 0 && s_size == |s|
requires forall x :: x in s <==> x in t
requires forall i, j :: (0 <= i < |t| && 0 <= j < |t| && i != j ) ==> t[i] != t[j]
requires |set x | x in t| == |t|
ensures |s| == |t|
decreases s_size {
if s_size == 0 {
} else {
var t_hd;
t_hd := t[0];
assert t_hd in s;
ghost var t_h := set x | x in t[1..];
assert |t_h| == |t[1..]|;
memebrship_implies_cardinality_helper(s - {t_hd}, t[1..], s_size - 1);
}
}
lemma memebrship_implies_cardinality<A>(s: set<A>, t: seq<A>)
requires forall x :: x in s <==> x in t
ensures |s| == |t| {
memebrship_implies_cardinality_helper(s, t, |s|);
}
*/
lemma set_memebrship_implies_equality_helper<A>(s: set<A>, t: set<A>, s_size: int)
requires s_size >= 0 && s_size == |s|
requires forall x :: x in s <==> x in t
ensures s == t
decreases s_size {
if s_size == 0 {
} else {
var s_hd;
// assign s_hd to a value *such that* s_hd is in s (see such_that expressions)
s_hd :| s_hd in s;
set_memebrship_implies_equality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);
}
}
lemma set_memebrship_implies_equality<A>(s: set<A>, t: set<A>)
requires forall x :: x in s <==> x in t
ensures s == t {
set_memebrship_implies_equality_helper(s, t, |s|);
}
// TODO play with this for keys==Contents
lemma set_seq_equality(s: set<int>, t: seq<int>)
requires distinct(t)
requires forall x :: x in t <==> x in s
{
var s2 : set<int> := set x | x in t;
set_memebrship_implies_equality_helper(s, s2, |s|);
assert |s2| == |s|;
// assert |s2| == |t|;
// assert |s| == |t|;
}
ghost predicate SortedSeq(a: seq<int>)
//sequence is sorted from left to right
{
(forall i,j :: 0<= i< j < |a| ==> ( a[i] < a[j] ))
}
method GetInsertIndex(a: array<int>, limit: int, x:int) returns (idx:int)
// get index so that array stays sorted
requires x !in a[..]
requires 0 <= limit <= a.Length
requires SortedSeq(a[..limit])
ensures 0<= idx <= limit
ensures SortedSeq(a[..limit])
ensures idx > 0 ==> a[idx-1]< x
ensures idx < limit ==> x < a[idx]
{
idx := limit;
for i := 0 to limit
invariant i>0 ==> x > a[i-1]
{
if x < a[i] {
idx := i;
break;
}
}
}
predicate sorted(a: seq<int>)
{
forall i,j :: 0 <= i < j < |a| ==> a[i] < a[j]
}
predicate distinct(a: seq<int>)
{
forall i,j :: (0 <= i < |a| && 0 <= j < |a| && i != j) ==> a[i] != a[j]
}
predicate sorted_eq(a: seq<int>)
{
forall i,j :: 0 <= i < j < |a| ==> a[i] <= a[j]
}
predicate lessThan(a:seq<int>, key:int) {
forall i :: 0 <= i < |a| ==> a[i] < key
}
predicate greaterThan(a:seq<int>, key:int) {
forall i :: 0 <= i < |a| ==> a[i] > key
}
predicate greaterEqualThan(a:seq<int>, key:int) {
forall i :: 0 <= i < |a| ==> a[i] >= key
}
/*
method InsertSorted(a: array<int>, key: int ) returns (b: array<int>)
requires sorted_eq(a[..])
ensures sorted_eq(b[..])
{
b:= new int[a.Length + 1];
ghost var k := 0;
b[0] := key;
ghost var a' := a[..];
var i:= 0;
while (i < a.Length)
modifies b
invariant 0 <= k <= i <= a.Length
invariant b.Length == a.Length + 1
invariant a[..] == a'
invariant lessThan(a[..i], key) ==> i == k
invariant lessThan(a[..k], key)
invariant b[..k] == a[..k]
invariant b[k] == key
invariant k < i ==> b[k+1..i+1] == a[k..i]
invariant k < i ==> greaterEqualThan(b[k+1..i+1], key)
invariant 0 <= k < b.Length && b[k] == key
{
if(a[i]<key)
{
b[i]:= a[i];
b[i+1] := key;
k := i+1;
}
else if (a[i] >= key)
{
b[i+1] := a[i];
}
i := i+1;
}
assert b[..] == a[..k] + [key] + a[k..];
}
*/
lemma DistributiveLemma(a: seq<bool>, b: seq<bool>)
ensures count(a + b) == count(a) + count(b)
{
if a == [] {
assert a + b == b;
} else {
DistributiveLemma(a[1..], b);
assert a + b == [a[0]] + (a[1..] + b);
}
}
function count(a: seq<bool>): nat
{
if |a| == 0 then 0 else
(if a[0] then 1 else 0) + count(a[1..])
}
lemma DistributiveIn(a: seq<int>, b:seq<int>, k:int, key:int)
requires |a| + 1 == |b|
requires 0 <= k <= |a|
requires b == a[..k] + [key] + a[k..]
ensures forall i :: 0 <= i < |a| ==> a[i] in b
{
assert forall j :: 0 <= j < k ==> a[j] in b;
assert forall j :: k <= j < |a| ==> a[j] in b;
assert ((forall j :: 0 <= j < k ==> a[j] in b) && (forall j :: k <= j < |a| ==> a[j] in b)) ==> (forall j :: 0 <= j < |a| ==> a[j] in b);
assert forall j :: 0 <= j < |a| ==> a[j] in b;
}
lemma DistributiveGreater(a: seq<int>, b:seq<int>, k:int, key:int)
requires |a| + 1 == |b|
requires 0 <= k <= |a|
requires b == a[..k] + [key] + a[k..]
requires forall j :: 0 <= j < |a| ==> a[j] > 0
requires key > 0
ensures forall i :: 0 <= i < |b| ==> b[i] > 0
{
// assert ((forall j :: 0 <= j < k ==> b[j] > 0) && (forall j :: k <= j < |a| ==> b[j] > 0)) ==> (forall j :: 0 <= j < |b| ==> b[j] > 0);
assert forall j :: 0 <= j < |b| ==> b[j] > 0;
}
// verifies in more than 45 seconds, but less than 100 seconds
method InsertIntoSorted(a: array<int>, limit:int, key:int) returns (b: array<int>)
requires key > 0
requires key !in a[..]
requires 0 <= limit < a.Length
requires forall i :: 0 <= i < limit ==> a[i] > 0
requires forall i :: limit <= i < a.Length ==> a[i] == 0
requires sorted(a[..limit])
ensures b.Length == a.Length
ensures sorted(b[..(limit+ 1)])
ensures forall i :: limit + 1 <= i < b.Length ==> b[i] == 0
ensures forall i :: 0 <= i < limit ==> a[i] in b[..]
ensures forall i :: 0 <= i < limit + 1 ==> b[i] > 0
{
b:= new int[a.Length];
ghost var k := 0;
b[0] := key;
ghost var a' := a[..];
var i:= 0;
while (i < limit)
modifies b
invariant 0 <= k <= i <= limit
invariant b.Length == a.Length
invariant a[..] == a'
invariant lessThan(a[..i], key) ==> i == k
invariant lessThan(a[..k], key)
invariant b[..k] == a[..k]
invariant b[k] == key
invariant k < i ==> b[k+1..i+1] == a[k..i]
invariant k < i ==> greaterThan(b[k+1..i+1], key)
invariant 0 <= k < b.Length && b[k] == key
{
if(a[i]<key)
{
b[i]:= a[i];
b[i+1] := key;
k := i+1;
}
else if (a[i] >= key)
{
b[i+1] := a[i];
}
i := i+1;
}
assert b[..limit+1] == a[..k] + [key] + a[k..limit];
assert sorted(b[..limit+1]);
// assert b[..limit+1] == a[..k] + [key] + a[k..limit];
DistributiveIn(a[..limit], b[..limit+1], k, key);
assert forall i :: 0 <= i < limit ==> a[i] in b[..limit+1];
DistributiveGreater(a[..limit], b[..limit+1], k, key);
// assert forall i :: 0 <= i < limit + 1 ==> b[i] > 0;
ghost var b' := b[..];
i := limit + 1;
while i < b.Length
invariant limit + 1 <= i <= b.Length
invariant forall j :: limit + 1 <= j < i ==> b[j] == 0
invariant b[..limit+1] == b'[..limit+1]
invariant sorted(b[..limit+1])
{
b[i] := 0;
i := i + 1;
}
assert forall i :: limit + 1 <= i < b.Length ==> b[i] == 0;
}
|
BPTree-verif_tmp_tmpq1z6xm1d_Utils.dfy
|
009
|
009
|
Dafny program: 009
|
//Bubblesort CS 494 submission
//References: https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny/69365785#69365785
// predicate checks if elements of a are in ascending order, two additional conditions are added to allow us to sort in specific range within array
predicate sorted(a:array<int>, from:int, to:int)
requires a != null; // requires array to have n amount of elements
reads a;
requires 0 <= from <= to <= a.Length; // pre condition checks that from is the start of the range and to is the end of the range, requires values to be within 0 - a.Length
{
forall x, y :: from <= x < y < to ==> a[x] <= a[y]
}
//helps ensure swapping is valid, it is used inside the nested while loop to make sure linear order is being kept
predicate pivot(a:array<int>, to:int, pvt:int)
requires a != null; // requires array to have n amount of elements
reads a;
requires 0 <= pvt < to <= a.Length;
{
forall x, y :: 0 <= x < pvt < y < to ==> a[x] <= a[y] // all values within the array should be in ascending order
}
// Here having the algorithm for the bubblesort
method BubbleSort (a: array<int>)
requires a != null && a.Length > 0; // makes sure a is not empty and length is greater than 0
modifies a; // as method runs, we are changing a
ensures sorted(a, 0, a.Length); // makes sure elements of array a are sorted from 0 - a.Length
ensures multiset(a[..]) == multiset(old(a[..])); // Since a is being modified, we deference the heap
//and compare the previous elements to current elements.
{
var i := 1;
while (i < a.Length)
{
var j := i;
//this while loop inherits any previous pre/post conditions. It checks that
while (j > 0)
{
// Here it also simplifies the remaining invariants to handle the empty array.
if (a[j-1] > a[j]) { // reverse iterate through range within the array
a[j - 1], a[j] := a[j], a[j - 1]; // swaps objects if the IF condition is met
}
j := j - 1; // decrement j
}
i := i+1; // increment i
}
}
|
//Bubblesort CS 494 submission
//References: https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny/69365785#69365785
// predicate checks if elements of a are in ascending order, two additional conditions are added to allow us to sort in specific range within array
predicate sorted(a:array<int>, from:int, to:int)
requires a != null; // requires array to have n amount of elements
reads a;
requires 0 <= from <= to <= a.Length; // pre condition checks that from is the start of the range and to is the end of the range, requires values to be within 0 - a.Length
{
forall x, y :: from <= x < y < to ==> a[x] <= a[y]
}
//helps ensure swapping is valid, it is used inside the nested while loop to make sure linear order is being kept
predicate pivot(a:array<int>, to:int, pvt:int)
requires a != null; // requires array to have n amount of elements
reads a;
requires 0 <= pvt < to <= a.Length;
{
forall x, y :: 0 <= x < pvt < y < to ==> a[x] <= a[y] // all values within the array should be in ascending order
}
// Here having the algorithm for the bubblesort
method BubbleSort (a: array<int>)
requires a != null && a.Length > 0; // makes sure a is not empty and length is greater than 0
modifies a; // as method runs, we are changing a
ensures sorted(a, 0, a.Length); // makes sure elements of array a are sorted from 0 - a.Length
ensures multiset(a[..]) == multiset(old(a[..])); // Since a is being modified, we deference the heap
//and compare the previous elements to current elements.
{
var i := 1;
while (i < a.Length)
invariant i <= a.Length; // more-or-less validates while loop condition during coputations
invariant sorted(a, 0, i); // Checks that for each increment of i, the array stays sorted, causing the
invariant multiset(a[..]) == multiset(old(a[..])); //makes sure elements that existed in previous heap for a are presnt in current run
{
var j := i;
//this while loop inherits any previous pre/post conditions. It checks that
while (j > 0)
invariant multiset(a[..]) == multiset(old(a[..]));
invariant sorted(a, 0, j); // O(n^2) runtime. Makes sure that a[0] - a[j] is sorted
invariant sorted(a, j, i+1); // then makes sure from a[j] - a[i+1] is sorted
invariant pivot(a, i+1, j); // important for ensuring that each computation is correct after swapping
{
// Here it also simplifies the remaining invariants to handle the empty array.
if (a[j-1] > a[j]) { // reverse iterate through range within the array
a[j - 1], a[j] := a[j], a[j - 1]; // swaps objects if the IF condition is met
}
j := j - 1; // decrement j
}
i := i+1; // increment i
}
}
|
CS494-final-project_tmp_tmp7nof55uq_bubblesort.dfy
|
010
|
010
|
Dafny program: 010
|
class LFUCache {
var capacity : int;
var cacheMap : map<int, (int, int)>; //key -> {value, freq}
constructor(capacity: int)
requires capacity > 0;
ensures Valid();
{
this.capacity := capacity;
this.cacheMap := map[];
}
predicate Valid()
reads this;
// reads this.freqMap.Values;
{
// general value check
this.capacity > 0 &&
0 <= |cacheMap| <= capacity &&
(|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].1 >= 1)) && // frequency should always larger than 0
(|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].0 >= 0)) // only allow positive values
}
method getLFUKey() returns (lfuKey : int)
requires Valid();
requires |cacheMap| > 0;
ensures Valid();
ensures lfuKey in cacheMap;
ensures forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;
{
var items := cacheMap.Items;
var seenItems := {};
var anyItem :| anyItem in items;
var minFreq := anyItem.1.1;
lfuKey := anyItem.0;
while items != {}
{
var item :| item in items;
if (item.1.1 < minFreq) {
lfuKey := item.0;
minFreq := item.1.1;
}
items := items - { item };
seenItems := seenItems + { item };
}
// assert forall k :: k in cacheMap ==> cacheMap[lfuKey].1 <= cacheMap[k].1; // ????
return lfuKey;
}
method get(key: int) returns (value: int)
requires Valid();
modifies this;
ensures Valid();
ensures key !in cacheMap ==> value == -1;
ensures forall e :: e in old(cacheMap) <==> e in cacheMap;
ensures forall e :: e in old(cacheMap) ==> (old(cacheMap[e].0) == cacheMap[e].0);
ensures key in cacheMap ==> value == cacheMap[key].0 && old(cacheMap[key].1) == cacheMap[key].1-1;
{
if(key !in cacheMap) {
value := -1;
}
else{
value := cacheMap[key].0;
var oldFreq := cacheMap[key].1;
var newV := (value, oldFreq + 1);
cacheMap := cacheMap[key := newV];
}
print "after get: ";
print cacheMap;
print "\n";
return value;
}
method put(key: int, value: int)
requires Valid();
requires value > 0;
modifies this
ensures Valid();
{
if (key in cacheMap) {
var currFreq := cacheMap[key].1;
cacheMap := cacheMap[key := (value, currFreq)];
} else {
if (|cacheMap| < capacity) {
cacheMap := cacheMap[key := (value, 1)];
} else {
var LFUKey := getLFUKey();
ghost var oldMap := cacheMap;
var newMap := cacheMap - {LFUKey};
cacheMap := newMap;
ghost var oldCard := |oldMap|;
ghost var newCard := |newMap|;
cacheMap := cacheMap[key := (value, 1)];
}
}
print "after put: ";
print cacheMap;
print "\n";
}
}
method Main()
{
var LFUCache := new LFUCache(5);
print "Cache Capacity = 5 \n";
print "PUT (1, 1) - ";
LFUCache.put(1,1);
print "PUT (2, 2) - ";
LFUCache.put(2,2);
print "PUT (3, 3) - ";
LFUCache.put(3,3);
print "GET (1) - ";
var val := LFUCache.get(1);
print "get(1) = ";
print val;
print "\n";
print "PUT (3, 5) - ";
LFUCache.put(3,5);
print "GET (3) - ";
val := LFUCache.get(3);
print "get(3) = ";
print val;
print "\n";
print "PUT (4, 6) - ";
LFUCache.put(4,6);
print "PUT (5, 7) - ";
LFUCache.put(5,7);
print "PUT (10, 100) - ";
LFUCache.put(10,100);
print "GET (2) - ";
val := LFUCache.get(2);
print "get(2) = ";
print val;
print "\n";
}
|
class LFUCache {
var capacity : int;
var cacheMap : map<int, (int, int)>; //key -> {value, freq}
constructor(capacity: int)
requires capacity > 0;
ensures Valid();
{
this.capacity := capacity;
this.cacheMap := map[];
}
predicate Valid()
reads this;
// reads this.freqMap.Values;
{
// general value check
this.capacity > 0 &&
0 <= |cacheMap| <= capacity &&
(|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].1 >= 1)) && // frequency should always larger than 0
(|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].0 >= 0)) // only allow positive values
}
method getLFUKey() returns (lfuKey : int)
requires Valid();
requires |cacheMap| > 0;
ensures Valid();
ensures lfuKey in cacheMap;
ensures forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;
{
var items := cacheMap.Items;
var seenItems := {};
var anyItem :| anyItem in items;
var minFreq := anyItem.1.1;
lfuKey := anyItem.0;
while items != {}
decreases |items|;
invariant cacheMap.Items >= items;
invariant cacheMap.Items >= seenItems;
invariant cacheMap.Items == seenItems + items;
invariant lfuKey in cacheMap;
invariant cacheMap[lfuKey].1 == minFreq;
invariant forall e :: e in seenItems ==> minFreq <= e.1.1;
invariant forall e :: e in seenItems ==> minFreq <= cacheMap[e.0].1;
invariant forall e :: e in seenItems ==> cacheMap[lfuKey].1 <= cacheMap[e.0].1;
invariant exists e :: e in seenItems + items ==> minFreq == e.1.1;
{
var item :| item in items;
if (item.1.1 < minFreq) {
lfuKey := item.0;
minFreq := item.1.1;
}
items := items - { item };
seenItems := seenItems + { item };
}
assert seenItems == cacheMap.Items;
assert cacheMap[lfuKey].1 == minFreq;
assert forall e :: e in seenItems ==> minFreq <= e.1.1;
assert forall e :: e in cacheMap.Items ==> minFreq <= e.1.1;
assert forall k :: k in seenItems ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;
assert forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;
// assert forall k :: k in cacheMap ==> cacheMap[lfuKey].1 <= cacheMap[k].1; // ????
return lfuKey;
}
method get(key: int) returns (value: int)
requires Valid();
modifies this;
ensures Valid();
ensures key !in cacheMap ==> value == -1;
ensures forall e :: e in old(cacheMap) <==> e in cacheMap;
ensures forall e :: e in old(cacheMap) ==> (old(cacheMap[e].0) == cacheMap[e].0);
ensures key in cacheMap ==> value == cacheMap[key].0 && old(cacheMap[key].1) == cacheMap[key].1-1;
{
assert key in cacheMap ==> cacheMap[key].0 >= 0;
if(key !in cacheMap) {
value := -1;
}
else{
assert key in cacheMap;
assert cacheMap[key].0 >= 0;
value := cacheMap[key].0;
var oldFreq := cacheMap[key].1;
var newV := (value, oldFreq + 1);
cacheMap := cacheMap[key := newV];
}
print "after get: ";
print cacheMap;
print "\n";
return value;
}
method put(key: int, value: int)
requires Valid();
requires value > 0;
modifies this
ensures Valid();
{
if (key in cacheMap) {
var currFreq := cacheMap[key].1;
cacheMap := cacheMap[key := (value, currFreq)];
} else {
if (|cacheMap| < capacity) {
cacheMap := cacheMap[key := (value, 1)];
} else {
var LFUKey := getLFUKey();
assert LFUKey in cacheMap;
assert |cacheMap| == capacity;
ghost var oldMap := cacheMap;
var newMap := cacheMap - {LFUKey};
cacheMap := newMap;
assert newMap == cacheMap - {LFUKey};
assert LFUKey !in cacheMap;
assert LFUKey in oldMap;
ghost var oldCard := |oldMap|;
ghost var newCard := |newMap|;
assert |cacheMap.Keys| < |oldMap|; // ????
cacheMap := cacheMap[key := (value, 1)];
}
}
print "after put: ";
print cacheMap;
print "\n";
}
}
method Main()
{
var LFUCache := new LFUCache(5);
print "Cache Capacity = 5 \n";
print "PUT (1, 1) - ";
LFUCache.put(1,1);
print "PUT (2, 2) - ";
LFUCache.put(2,2);
print "PUT (3, 3) - ";
LFUCache.put(3,3);
print "GET (1) - ";
var val := LFUCache.get(1);
print "get(1) = ";
print val;
print "\n";
print "PUT (3, 5) - ";
LFUCache.put(3,5);
print "GET (3) - ";
val := LFUCache.get(3);
print "get(3) = ";
print val;
print "\n";
print "PUT (4, 6) - ";
LFUCache.put(4,6);
print "PUT (5, 7) - ";
LFUCache.put(5,7);
print "PUT (10, 100) - ";
LFUCache.put(10,100);
print "GET (2) - ";
val := LFUCache.get(2);
print "get(2) = ";
print val;
print "\n";
}
|
CS5232_Project_tmp_tmpai_cfrng_LFUSimple.dfy
|
011
|
011
|
Dafny program: 011
|
iterator Gen(start: int) yields (x: int)
yield ensures |xs| <= 10 && x == start + |xs| - 1
{
var i := 0;
while i < 10 invariant |xs| == i {
x := start + i;
yield;
i := i + 1;
}
}
method Main() {
var i := new Gen(30);
while true
{
var m := i.MoveNext();
if (!m) {break; }
print i.x;
}
}
|
iterator Gen(start: int) yields (x: int)
yield ensures |xs| <= 10 && x == start + |xs| - 1
{
var i := 0;
while i < 10 invariant |xs| == i {
x := start + i;
yield;
i := i + 1;
}
}
method Main() {
var i := new Gen(30);
while true
invariant i.Valid() && fresh(i._new)
decreases 10 - |i.xs|
{
var m := i.MoveNext();
if (!m) {break; }
print i.x;
}
}
|
CS5232_Project_tmp_tmpai_cfrng_test.dfy
|
014
|
014
|
Dafny program: 014
|
method Max (x: nat, y:nat) returns (r:nat)
ensures (r >= x && r >=y)
ensures (r == x || r == y)
{
if (x >= y) { r := x;}
else { r := y;}
}
method Test ()
{
var result := Max(42, 73);
}
method m1 (x: int, y: int) returns (z: int)
requires 0 < x < y
ensures z >= 0 && z <= y && z != x
{
//assume 0 < x < y
z := 0;
}
function fib (n: nat) : nat
{
if n == 0 then 1 else
if n == 1 then 1 else
fib(n -1) + fib (n-2)
}
method Fib (n: nat) returns (r:nat)
ensures r == fib(n)
{
if (n == 0) {
return 1;
}
r := 1;
var next:=2;
var i := 1;
while i < n
{
var tmp:=next;
next:= next + r;
r:= tmp;
i:= i + 1;
}
return r;
}
datatype List<T> = Nil | Cons(head: T, tail: List<T>)
function add(l:List<int>) : int
{
match l
case Nil => 0
case Cons(x, xs) => x + add(xs)
}
method addImp (l: List<int>) returns (s: int)
ensures s == add(l)
{
var ll := l;
s := 0;
while ll != Nil
{
s := s + ll.head;
ll:= ll.tail;
}
}
method MaxA (a: array<int>) returns (m: int)
requires a.Length > 0
ensures forall i :: 0 <= i < a.Length ==> a[i] <= m
ensures exists i :: 0 <= i < a.Length && a[i] == m
{
m := a[0];
var i := 1;
while i< a.Length
{
if a[i] > m {
m:= a[i];
}
i := i +1;
}
}
|
method Max (x: nat, y:nat) returns (r:nat)
ensures (r >= x && r >=y)
ensures (r == x || r == y)
{
if (x >= y) { r := x;}
else { r := y;}
}
method Test ()
{
var result := Max(42, 73);
assert result == 73;
}
method m1 (x: int, y: int) returns (z: int)
requires 0 < x < y
ensures z >= 0 && z <= y && z != x
{
//assume 0 < x < y
z := 0;
}
function fib (n: nat) : nat
{
if n == 0 then 1 else
if n == 1 then 1 else
fib(n -1) + fib (n-2)
}
method Fib (n: nat) returns (r:nat)
ensures r == fib(n)
{
if (n == 0) {
return 1;
}
r := 1;
var next:=2;
var i := 1;
while i < n
invariant 1 <= i <= n
invariant r == fib(i)
invariant next == fib(i+1)
{
var tmp:=next;
next:= next + r;
r:= tmp;
i:= i + 1;
}
assert r == fib(n);
return r;
}
datatype List<T> = Nil | Cons(head: T, tail: List<T>)
function add(l:List<int>) : int
{
match l
case Nil => 0
case Cons(x, xs) => x + add(xs)
}
method addImp (l: List<int>) returns (s: int)
ensures s == add(l)
{
var ll := l;
s := 0;
while ll != Nil
decreases ll
invariant add(l) == s + add(ll)
{
s := s + ll.head;
ll:= ll.tail;
}
assert s == add(l);
}
method MaxA (a: array<int>) returns (m: int)
requires a.Length > 0
ensures forall i :: 0 <= i < a.Length ==> a[i] <= m
ensures exists i :: 0 <= i < a.Length && a[i] == m
{
m := a[0];
var i := 1;
while i< a.Length
invariant 1 <= i <= a.Length
invariant forall j :: 0 <= j < i ==> a[j] <=m
invariant exists j :: 0 <= j < i && a[j] ==m
{
if a[i] > m {
m:= a[i];
}
i := i +1;
}
}
|
CVS-Projto1_tmp_tmpb1o0bu8z_Hoare.dfy
|
016
|
016
|
Dafny program: 016
|
//Exercicio 1.a)
function sum (a:array<int>, i:int, j:int) :int
reads a
requires 0 <= i <= j <= a.Length
{
if i == j then
0
else
a[j-1] + sum(a, i, j-1)
}
//Exercicio 1.b)
method query (a:array<int>, i:int, j:int) returns (s:int)
requires 0 <= i <= j <= a.Length
ensures s == sum(a, i, j)
{
s := 0;
var aux := i;
while (aux < j)
{
s := s + a[aux];
aux := aux + 1;
}
return s;
}
//Exercicio 1.c)
lemma queryLemma(a:array<int>, i:int, j:int, k:int)
requires 0 <= i <= k <= j <= a.Length
ensures sum(a,i,k) + sum(a,k,j) == sum(a,i,j)
{
}
method queryFast (a:array<int>, c:array<int>, i:int, j:int) returns (r:int)
requires is_prefix_sum_for(a,c) && 0 <= i <= j <= a.Length < c.Length
ensures r == sum(a, i,j)
{
r := c[j] - c[i];
queryLemma(a,0,j,i);
return r;
}
predicate is_prefix_sum_for (a:array<int>, c:array<int>)
reads c, a
{
a.Length + 1 == c.Length
&& c[0] == 0
&& forall j :: 1 <= j <= a.Length ==> c[j] == sum(a,0,j)
}
///Exercicio 2.
datatype List<T> = Nil | Cons(head: T, tail: List<T>)
method from_array<T>(a: array<T>) returns (l: List<T>)
requires a.Length > 0
ensures forall j::0 <= j < a.Length ==> mem(a[j],l)
{
var i:= a.Length-1;
l:= Nil;
while (i >= 0)
{
l := Cons(a[i], l);
i := i - 1;
}
return l;
}
function mem<T(==)> (x: T, l:List<T>) : bool
{
match l
case Nil => false
case Cons(y,r)=> if (x==y) then true else mem(x,r)
}
|
//Exercicio 1.a)
function sum (a:array<int>, i:int, j:int) :int
decreases j
reads a
requires 0 <= i <= j <= a.Length
{
if i == j then
0
else
a[j-1] + sum(a, i, j-1)
}
//Exercicio 1.b)
method query (a:array<int>, i:int, j:int) returns (s:int)
requires 0 <= i <= j <= a.Length
ensures s == sum(a, i, j)
{
s := 0;
var aux := i;
while (aux < j)
invariant i <= aux <= j
invariant s == sum(a, i, aux)
decreases j - aux
{
s := s + a[aux];
aux := aux + 1;
}
return s;
}
//Exercicio 1.c)
lemma queryLemma(a:array<int>, i:int, j:int, k:int)
requires 0 <= i <= k <= j <= a.Length
ensures sum(a,i,k) + sum(a,k,j) == sum(a,i,j)
{
}
method queryFast (a:array<int>, c:array<int>, i:int, j:int) returns (r:int)
requires is_prefix_sum_for(a,c) && 0 <= i <= j <= a.Length < c.Length
ensures r == sum(a, i,j)
{
r := c[j] - c[i];
queryLemma(a,0,j,i);
return r;
}
predicate is_prefix_sum_for (a:array<int>, c:array<int>)
reads c, a
{
a.Length + 1 == c.Length
&& c[0] == 0
&& forall j :: 1 <= j <= a.Length ==> c[j] == sum(a,0,j)
}
///Exercicio 2.
datatype List<T> = Nil | Cons(head: T, tail: List<T>)
method from_array<T>(a: array<T>) returns (l: List<T>)
requires a.Length > 0
ensures forall j::0 <= j < a.Length ==> mem(a[j],l)
{
var i:= a.Length-1;
l:= Nil;
while (i >= 0)
invariant -1 <= i < a. Length
invariant forall j:: i+1 <= j < a.Length ==> mem(a[j],l)
{
l := Cons(a[i], l);
i := i - 1;
}
return l;
}
function mem<T(==)> (x: T, l:List<T>) : bool
decreases l
{
match l
case Nil => false
case Cons(y,r)=> if (x==y) then true else mem(x,r)
}
|
CVS-Projto1_tmp_tmpb1o0bu8z_proj1_proj1.dfy
|
018
|
018
|
Dafny program: 018
|
/* Cumulative Sums over Arrays */
/*
Daniel Cavalheiro 57869
Pedro Nunes 57854
*/
//(a)
function sum(a: array<int>, i: int, j: int): int
reads a
requires 0 <= i <= j <= a.Length
{
if (i == j) then 0
else a[i] + sum(a, i+1, j)
}
//(b)
method query(a: array<int>, i: int, j: int) returns (res:int)
requires 0 <= i <= j <= a.Length
ensures res == sum(a, i, j)
{
res := 0;
var k := i;
while(k < j)
{
res := res + a[k];
k := k + 1;
}
}
//(c)
predicate is_prefix_sum_for (a: array<int>, c: array<int>)
requires a.Length + 1 == c.Length
requires c[0] == 0
reads c, a
{
forall i: int :: 0 <= i < a.Length ==> c[i+1] == c[i] + a[i]
}
lemma aux(a: array<int>, c: array<int>, i: int, j: int)
requires 0 <= i <= j <= a.Length
requires a.Length + 1 == c.Length
requires c[0] == 0
requires is_prefix_sum_for(a, c)
ensures forall k: int :: i <= k <= j ==> sum(a, i, k) + sum(a, k, j) == c[k] - c[i] + c[j] - c[k] //sum(a, i, j) == c[j] - c[i]
{}
method queryFast(a: array<int>, c: array<int>, i: int, j: int) returns (r: int)
requires a.Length + 1 == c.Length && c[0] == 0
requires 0 <= i <= j <= a.Length
requires is_prefix_sum_for(a,c)
ensures r == sum(a, i, j)
{
aux(a, c, i, j);
r := c[j] - c[i];
}
method Main()
{
var x := new int[10];
x[0], x[1], x[2], x[3] := 2, 2, 1, 5;
var y := sum(x, 0, x.Length);
//assert y == 10;
var c := new int[11];
c[0], c[1], c[2], c[3], c[4] := 0, 2, 4, 5, 10;
// var r := queryFast(x, c, 0, x.Length);
}
|
/* Cumulative Sums over Arrays */
/*
Daniel Cavalheiro 57869
Pedro Nunes 57854
*/
//(a)
function sum(a: array<int>, i: int, j: int): int
reads a
requires 0 <= i <= j <= a.Length
decreases j - i
{
if (i == j) then 0
else a[i] + sum(a, i+1, j)
}
//(b)
method query(a: array<int>, i: int, j: int) returns (res:int)
requires 0 <= i <= j <= a.Length
ensures res == sum(a, i, j)
{
res := 0;
var k := i;
while(k < j)
invariant i <= k <= j <= a.Length
invariant res + sum(a, k, j) == sum(a, i, j)
{
res := res + a[k];
k := k + 1;
}
}
//(c)
predicate is_prefix_sum_for (a: array<int>, c: array<int>)
requires a.Length + 1 == c.Length
requires c[0] == 0
reads c, a
{
forall i: int :: 0 <= i < a.Length ==> c[i+1] == c[i] + a[i]
}
lemma aux(a: array<int>, c: array<int>, i: int, j: int)
requires 0 <= i <= j <= a.Length
requires a.Length + 1 == c.Length
requires c[0] == 0
requires is_prefix_sum_for(a, c)
decreases j - i
ensures forall k: int :: i <= k <= j ==> sum(a, i, k) + sum(a, k, j) == c[k] - c[i] + c[j] - c[k] //sum(a, i, j) == c[j] - c[i]
{}
method queryFast(a: array<int>, c: array<int>, i: int, j: int) returns (r: int)
requires a.Length + 1 == c.Length && c[0] == 0
requires 0 <= i <= j <= a.Length
requires is_prefix_sum_for(a,c)
ensures r == sum(a, i, j)
{
aux(a, c, i, j);
r := c[j] - c[i];
}
method Main()
{
var x := new int[10];
x[0], x[1], x[2], x[3] := 2, 2, 1, 5;
var y := sum(x, 0, x.Length);
//assert y == 10;
var c := new int[11];
c[0], c[1], c[2], c[3], c[4] := 0, 2, 4, 5, 10;
// var r := queryFast(x, c, 0, x.Length);
}
|
CVS-handout1_tmp_tmptm52no3k_1.dfy
|
019
|
019
|
Dafny program: 019
|
/* Functional Lists and Imperative Arrays */
/*
Daniel Cavalheiro 57869
Pedro Nunes 57854
*/
datatype List<T> = Nil | Cons(head: T, tail: List<T>)
function length<T>(l: List<T>): nat
{
match l
case Nil => 0
case Cons(_, t) => 1 + length(t)
}
predicate mem<T(==)> (l: List<T>, x: T)
{
match l
case Nil => false
case Cons(h, t) => if(h == x) then true else mem(t, x)
}
function at<T>(l: List<T>, i: nat): T
requires i < length(l)
{
if i == 0 then l.head else at(l.tail, i - 1)
}
method from_array<T>(a: array<T>) returns (l: List<T>)
requires a.Length >= 0
ensures length(l) == a.Length
ensures forall i: int :: 0 <= i < length(l) ==> at(l, i) == a[i]
ensures forall x :: mem(l, x) ==> exists i: int :: 0 <= i < length(l) && a[i] == x
{
l := Nil;
var i: int := a.Length - 1;
while(i >= 0)
{
l := Cons(a[i], l);
i := i-1;
}
}
method Main() {
var l: List<int> := List.Cons(1, List.Cons(2, List.Cons(3, Nil)));
var arr: array<int> := new int [3](i => i + 1);
var t: List<int> := from_array(arr);
print l;
print "\n";
print t;
print "\n";
print t == l;
}
|
/* Functional Lists and Imperative Arrays */
/*
Daniel Cavalheiro 57869
Pedro Nunes 57854
*/
datatype List<T> = Nil | Cons(head: T, tail: List<T>)
function length<T>(l: List<T>): nat
{
match l
case Nil => 0
case Cons(_, t) => 1 + length(t)
}
predicate mem<T(==)> (l: List<T>, x: T)
{
match l
case Nil => false
case Cons(h, t) => if(h == x) then true else mem(t, x)
}
function at<T>(l: List<T>, i: nat): T
requires i < length(l)
{
if i == 0 then l.head else at(l.tail, i - 1)
}
method from_array<T>(a: array<T>) returns (l: List<T>)
requires a.Length >= 0
ensures length(l) == a.Length
ensures forall i: int :: 0 <= i < length(l) ==> at(l, i) == a[i]
ensures forall x :: mem(l, x) ==> exists i: int :: 0 <= i < length(l) && a[i] == x
{
l := Nil;
var i: int := a.Length - 1;
while(i >= 0)
invariant -1 <= i <= a.Length - 1
invariant length(l) == a.Length - 1 - i
invariant forall j: int :: i < j < a.Length ==> at(l,j-i-1) == a[j]
invariant forall x :: mem(l, x) ==> exists k: int :: i < k < a.Length && a[k] == x
{
l := Cons(a[i], l);
i := i-1;
}
}
method Main() {
var l: List<int> := List.Cons(1, List.Cons(2, List.Cons(3, Nil)));
var arr: array<int> := new int [3](i => i + 1);
var t: List<int> := from_array(arr);
print l;
print "\n";
print t;
print "\n";
print t == l;
}
|
CVS-handout1_tmp_tmptm52no3k_2.dfy
|
021
|
021
|
Dafny program: 021
|
method allDigits(s: string) returns (result: bool)
ensures result <==> (forall i :: 0 <= i < |s| ==> s[i] in "0123456789")
{
result:=true ;
for i := 0 to |s|
{
if ! (s[i] in "0123456789"){
return false;
}
}
}
|
method allDigits(s: string) returns (result: bool)
ensures result <==> (forall i :: 0 <= i < |s| ==> s[i] in "0123456789")
{
result:=true ;
for i := 0 to |s|
invariant result <==> (forall ii :: 0 <= ii < i ==> s[ii] in "0123456789")
{
if ! (s[i] in "0123456789"){
return false;
}
}
}
|
Clover_all_digits.dfy
|
022
|
022
|
Dafny program: 022
|
method append(a:array<int>, b:int) returns (c:array<int>)
ensures a[..] + [b] == c[..]
{
c := new int[a.Length+1];
var i:= 0;
while (i < a.Length)
{
c[i] := a[i];
i:=i+1;
}
c[a.Length]:=b;
}
|
method append(a:array<int>, b:int) returns (c:array<int>)
ensures a[..] + [b] == c[..]
{
c := new int[a.Length+1];
var i:= 0;
while (i < a.Length)
invariant 0 <= i <= a.Length
invariant forall ii::0<=ii<i ==> c[ii]==a[ii]
{
c[i] := a[i];
i:=i+1;
}
c[a.Length]:=b;
}
|
Clover_array_append.dfy
|
023
|
023
|
Dafny program: 023
|
method concat(a:array<int>, b:array<int>) returns (c:array<int>)
ensures c.Length==b.Length+a.Length
ensures forall k :: 0 <= k < a.Length ==> c[k] == a[k]
ensures forall k :: 0 <= k < b.Length ==> c[k+a.Length] == b[k]
{
c := new int[a.Length+b.Length];
var i:= 0;
while (i < c.Length)
{
c[i] := if i<a.Length then a[i] else b[i-a.Length];
i:=i+1;
}
}
|
method concat(a:array<int>, b:array<int>) returns (c:array<int>)
ensures c.Length==b.Length+a.Length
ensures forall k :: 0 <= k < a.Length ==> c[k] == a[k]
ensures forall k :: 0 <= k < b.Length ==> c[k+a.Length] == b[k]
{
c := new int[a.Length+b.Length];
var i:= 0;
while (i < c.Length)
invariant 0 <= i <= c.Length
invariant if i<a.Length then c[..i]==a[..i] else c[..i]==a[..]+b[..(i-a.Length)]
{
c[i] := if i<a.Length then a[i] else b[i-a.Length];
i:=i+1;
}
}
|
Clover_array_concat.dfy
|
024
|
024
|
Dafny program: 024
|
method iter_copy<T(0)>(s: array<T>) returns (t: array<T>)
ensures s.Length==t.Length
ensures forall i::0<=i<s.Length ==> s[i]==t[i]
{
t := new T[s.Length];
var i:= 0;
while (i < s.Length)
{
t[i] := s[i];
i:=i+1;
}
}
|
method iter_copy<T(0)>(s: array<T>) returns (t: array<T>)
ensures s.Length==t.Length
ensures forall i::0<=i<s.Length ==> s[i]==t[i]
{
t := new T[s.Length];
var i:= 0;
while (i < s.Length)
invariant 0 <= i <= s.Length
invariant forall x :: 0 <= x < i ==> s[x] == t[x]
{
t[i] := s[i];
i:=i+1;
}
}
|
Clover_array_copy.dfy
|
025
|
025
|
Dafny program: 025
|
method arrayProduct(a: array<int>, b: array<int>) returns (c: array<int> )
requires a.Length==b.Length
ensures c.Length==a.Length
ensures forall i:: 0 <= i< a.Length==> a[i] * b[i]==c[i]
{
c:= new int[a.Length];
var i:=0;
while i<a.Length
{
c[i]:=a[i]*b[i];
i:=i+1;
}
}
|
method arrayProduct(a: array<int>, b: array<int>) returns (c: array<int> )
requires a.Length==b.Length
ensures c.Length==a.Length
ensures forall i:: 0 <= i< a.Length==> a[i] * b[i]==c[i]
{
c:= new int[a.Length];
var i:=0;
while i<a.Length
invariant 0<=i<=a.Length
invariant forall j:: 0 <= j< i==> a[j] * b[j]==c[j]
{
c[i]:=a[i]*b[i];
i:=i+1;
}
}
|
Clover_array_product.dfy
|
026
|
026
|
Dafny program: 026
|
method arraySum(a: array<int>, b: array<int>) returns (c: array<int> )
requires a.Length==b.Length
ensures c.Length==a.Length
ensures forall i:: 0 <= i< a.Length==> a[i] + b[i]==c[i]
{
c:= new int[a.Length];
var i:=0;
while i<a.Length
{
c[i]:=a[i]+b[i];
i:=i+1;
}
}
|
method arraySum(a: array<int>, b: array<int>) returns (c: array<int> )
requires a.Length==b.Length
ensures c.Length==a.Length
ensures forall i:: 0 <= i< a.Length==> a[i] + b[i]==c[i]
{
c:= new int[a.Length];
var i:=0;
while i<a.Length
invariant 0<=i<=a.Length
invariant forall j:: 0 <= j< i==> a[j] + b[j]==c[j]
{
c[i]:=a[i]+b[i];
i:=i+1;
}
}
|
Clover_array_sum.dfy
|
028
|
028
|
Dafny program: 028
|
method below_zero(operations: seq<int>) returns (s:array<int>, result:bool)
ensures s.Length == |operations| + 1
ensures s[0]==0
ensures forall i :: 0 <= i < s.Length-1 ==> s[i+1]==s[i]+operations[i]
ensures result == true ==> (exists i :: 1 <= i <= |operations| && s[i] < 0)
ensures result == false ==> forall i :: 0 <= i < s.Length ==> s[i] >= 0
{
result := false;
s := new int[|operations| + 1];
var i := 0;
s[i] := 0;
while i < s.Length
{
if i>0{
s[i] := s[i - 1] + operations[i - 1];
}
i := i + 1;
}
i:=0;
while i < s.Length
{
if s[i] < 0 {
result := true;
return;
}
i := i + 1;
}
}
|
method below_zero(operations: seq<int>) returns (s:array<int>, result:bool)
ensures s.Length == |operations| + 1
ensures s[0]==0
ensures forall i :: 0 <= i < s.Length-1 ==> s[i+1]==s[i]+operations[i]
ensures result == true ==> (exists i :: 1 <= i <= |operations| && s[i] < 0)
ensures result == false ==> forall i :: 0 <= i < s.Length ==> s[i] >= 0
{
result := false;
s := new int[|operations| + 1];
var i := 0;
s[i] := 0;
while i < s.Length
invariant 0 <= i <= s.Length
invariant s[0]==0
invariant s.Length == |operations| + 1
invariant forall x :: 0 <= x < i-1 ==> s[x+1]==s[x]+operations[x]
{
if i>0{
s[i] := s[i - 1] + operations[i - 1];
}
i := i + 1;
}
i:=0;
while i < s.Length
invariant 0 <= i <= s.Length
invariant forall x :: 0 <= x < i ==> s[x] >= 0
{
if s[i] < 0 {
result := true;
return;
}
i := i + 1;
}
}
|
Clover_below_zero.dfy
|
029
|
029
|
Dafny program: 029
|
method BinarySearch(a: array<int>, key: int) returns (n: int)
requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j]
ensures 0<= n <=a.Length
ensures forall i :: 0<= i < n ==> a[i] < key
ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] < key
ensures forall i :: n<= i < a.Length ==> a[i]>=key
{
var lo, hi := 0, a.Length;
while lo<hi
{
var mid := (lo + hi) / 2;
if a[mid] < key {
lo := mid + 1;
} else {
hi := mid;
}
}
n:=lo;
}
|
method BinarySearch(a: array<int>, key: int) returns (n: int)
requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j]
ensures 0<= n <=a.Length
ensures forall i :: 0<= i < n ==> a[i] < key
ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] < key
ensures forall i :: n<= i < a.Length ==> a[i]>=key
{
var lo, hi := 0, a.Length;
while lo<hi
invariant 0<= lo <= hi <= a.Length
invariant forall i :: 0<=i<lo ==> a[i] < key
invariant forall i :: hi<=i<a.Length ==> a[i] >= key
{
var mid := (lo + hi) / 2;
if a[mid] < key {
lo := mid + 1;
} else {
hi := mid;
}
}
n:=lo;
}
|
Clover_binary_search.dfy
|
030
|
030
|
Dafny program: 030
|
method BubbleSort(a: array<int>)
modifies a
ensures forall i,j::0<= i < j < a.Length ==> a[i] <= a[j]
ensures multiset(a[..])==multiset(old(a[..]))
{
var i := a.Length - 1;
while (i > 0)
{
var j := 0;
while (j < i)
{
if (a[j] > a[j + 1])
{
a[j], a[j + 1] := a[j + 1], a[j];
}
j := j + 1;
}
i := i - 1;
}
}
|
method BubbleSort(a: array<int>)
modifies a
ensures forall i,j::0<= i < j < a.Length ==> a[i] <= a[j]
ensures multiset(a[..])==multiset(old(a[..]))
{
var i := a.Length - 1;
while (i > 0)
invariant i < 0 ==> a.Length == 0
invariant -1 <= i < a.Length
invariant forall ii,jj::i <= ii< jj <a.Length ==> a[ii] <= a[jj]
invariant forall k,k'::0<=k<=i<k'<a.Length==>a[k]<=a[k']
invariant multiset(a[..])==multiset(old(a[..]))
{
var j := 0;
while (j < i)
invariant 0 < i < a.Length && 0 <= j <= i
invariant forall ii,jj::i<= ii <= jj <a.Length ==> a[ii] <= a[jj]
invariant forall k, k'::0<=k<=i<k'<a.Length==>a[k]<=a[k']
invariant forall k :: 0 <= k <= j ==> a[k] <= a[j]
invariant multiset(a[..])==multiset(old(a[..]))
{
if (a[j] > a[j + 1])
{
a[j], a[j + 1] := a[j + 1], a[j];
}
j := j + 1;
}
i := i - 1;
}
}
|
Clover_bubble_sort.dfy
|
031
|
031
|
Dafny program: 031
|
method CalDiv() returns (x:int, y:int)
ensures x==191/7
ensures y==191%7
{
x, y := 0, 191;
while 7 <= y
{
x := x+1;
y:=191-7*x;
}
}
|
method CalDiv() returns (x:int, y:int)
ensures x==191/7
ensures y==191%7
{
x, y := 0, 191;
while 7 <= y
invariant 0 <= y && 7 * x + y == 191
{
x := x+1;
y:=191-7*x;
}
}
|
Clover_cal_ans.dfy
|
032
|
032
|
Dafny program: 032
|
method Sum(N:int) returns (s:int)
requires N >= 0
ensures s == N * (N + 1) / 2
{
var n := 0;
s := 0;
while n != N
{
n := n + 1;
s := s + n;
}
}
|
method Sum(N:int) returns (s:int)
requires N >= 0
ensures s == N * (N + 1) / 2
{
var n := 0;
s := 0;
while n != N
invariant 0 <= n <= N
invariant s == n * (n + 1) / 2
{
n := n + 1;
s := s + n;
}
}
|
Clover_cal_sum.dfy
|
033
|
033
|
Dafny program: 033
|
method CanyonSearch(a: array<int>, b: array<int>) returns (d:nat)
requires a.Length !=0 && b.Length!=0
requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j]
requires forall i,j :: 0<=i<j<b.Length ==> b[i]<=b[j]
ensures exists i,j:: 0<=i<a.Length && 0<=j<b.Length && d==if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j])
ensures forall i,j:: 0<=i<a.Length && 0<=j<b.Length ==> d<=if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j])
{
var m,n:=0,0;
d:=if a[0] < b[0] then (b[0]-a[0]) else (a[0]-b[0]);
while m<a.Length && n<b.Length
{
var t := if a[m] < b[n] then (b[n]-a[m]) else (a[m]-b[n]);
d:=if t<d then t else d;
if
case a[m]<=b[n] =>
m:=m+1;
case b[n]<=a[m] =>
n:=n+1;
}
}
|
method CanyonSearch(a: array<int>, b: array<int>) returns (d:nat)
requires a.Length !=0 && b.Length!=0
requires forall i,j :: 0<=i<j<a.Length ==> a[i]<=a[j]
requires forall i,j :: 0<=i<j<b.Length ==> b[i]<=b[j]
ensures exists i,j:: 0<=i<a.Length && 0<=j<b.Length && d==if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j])
ensures forall i,j:: 0<=i<a.Length && 0<=j<b.Length ==> d<=if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j])
{
var m,n:=0,0;
d:=if a[0] < b[0] then (b[0]-a[0]) else (a[0]-b[0]);
while m<a.Length && n<b.Length
invariant 0<=m<=a.Length && 0<=n<=b.Length
decreases a.Length -m+b.Length-n
invariant exists i,j:: 0<=i<a.Length && 0<=j<b.Length && d==if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j])
invariant forall i,j:: 0<=i<a.Length && 0<=j<b.Length ==> d<=(if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]))|| (m<=i&&n<=j)
{
var t := if a[m] < b[n] then (b[n]-a[m]) else (a[m]-b[n]);
d:=if t<d then t else d;
if
case a[m]<=b[n] =>
m:=m+1;
case b[n]<=a[m] =>
n:=n+1;
}
}
|
Clover_canyon_search.dfy
|
036
|
036
|
Dafny program: 036
|
method copy( src: array<int>, sStart: nat, dest: array<int>, dStart: nat, len: nat) returns (r: array<int>)
requires src.Length >= sStart + len
requires dest.Length >= dStart + len
ensures r.Length == dest.Length
ensures r[..dStart] == dest[..dStart]
ensures r[dStart + len..] == dest[dStart + len..]
ensures r[dStart..len+dStart] == src[sStart..len+sStart]
{
if len == 0 { return dest; }
var i: nat := 0;
r := new int[dest.Length];
while (i < r.Length)
{
r[i] := dest[i];
i := i + 1;
}
i := 0;
while (i < len)
{
r[dStart + i] := src[sStart + i];
i := i + 1;
}
}
|
method copy( src: array<int>, sStart: nat, dest: array<int>, dStart: nat, len: nat) returns (r: array<int>)
requires src.Length >= sStart + len
requires dest.Length >= dStart + len
ensures r.Length == dest.Length
ensures r[..dStart] == dest[..dStart]
ensures r[dStart + len..] == dest[dStart + len..]
ensures r[dStart..len+dStart] == src[sStart..len+sStart]
{
if len == 0 { return dest; }
var i: nat := 0;
r := new int[dest.Length];
while (i < r.Length)
invariant i <= r.Length
invariant r[..i] == dest[..i]
{
r[i] := dest[i];
i := i + 1;
}
assert r[..]==dest[..];
i := 0;
while (i < len)
invariant i <= len
invariant r[..dStart] == dest[..dStart]
invariant r[(dStart + len)..] == dest[(dStart + len)..]
invariant r[dStart .. dStart + i] == src[sStart .. sStart + i]
{
assert r[(dStart + len)..] == dest[(dStart + len)..];
r[dStart + i] := src[sStart + i];
i := i + 1;
}
}
|
Clover_copy_part.dfy
|
037
|
037
|
Dafny program: 037
|
method CountLessThan(numbers: set<int>, threshold: int) returns (count: int)
ensures count == |set i | i in numbers && i < threshold|
{
count := 0;
var shrink := numbers;
var grow := {};
while |shrink | > 0
{
var i: int :| i in shrink;
shrink := shrink - {i};
var grow' := grow+{i};
grow := grow + {i};
if i < threshold {
count := count + 1;
}
}
}
|
method CountLessThan(numbers: set<int>, threshold: int) returns (count: int)
ensures count == |set i | i in numbers && i < threshold|
{
count := 0;
var shrink := numbers;
var grow := {};
while |shrink | > 0
decreases shrink
invariant shrink + grow == numbers
invariant grow !! shrink
invariant count == |set i | i in grow && i < threshold|
{
var i: int :| i in shrink;
shrink := shrink - {i};
var grow' := grow+{i};
assert (set i | i in grow' && i < threshold) ==
(set i | i in grow && i < threshold )+ if i < threshold then {i} else {};
grow := grow + {i};
if i < threshold {
count := count + 1;
}
}
}
|
Clover_count_lessthan.dfy
|
038
|
038
|
Dafny program: 038
|
method double_array_elements(s: array<int>)
modifies s
ensures forall i :: 0 <= i < s.Length ==> s[i] == 2 * old(s[i])
{
var i:= 0;
while (i < s.Length)
{
s[i] := 2 * s[i];
i := i + 1;
}
}
|
method double_array_elements(s: array<int>)
modifies s
ensures forall i :: 0 <= i < s.Length ==> s[i] == 2 * old(s[i])
{
var i:= 0;
while (i < s.Length)
invariant 0 <= i <= s.Length
invariant forall x :: i <= x < s.Length ==> s[x] == old(s[x])
invariant forall x :: 0 <= x < i ==> s[x] == 2 * old(s[x])
{
s[i] := 2 * s[i];
i := i + 1;
}
}
|
Clover_double_array_elements.dfy
|
040
|
040
|
Dafny program: 040
|
method FindEvenNumbers (arr: array<int>) returns (evenNumbers: array<int>)
ensures forall x {:trigger (x%2) }:: x in arr[..] && (x%2==0)==> x in evenNumbers[..]
ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..]
ensures forall k :: 0 <= k < evenNumbers.Length ==> evenNumbers[k] % 2 == 0
ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==>
exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m]
{
var evenList: seq<int> := [];
ghost var indices: seq<int> := [];
for i := 0 to arr.Length
{
if arr[i]%2==0
{
evenList := evenList + [arr[i]];
indices := indices + [i];
}
}
evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]);
}
|
method FindEvenNumbers (arr: array<int>) returns (evenNumbers: array<int>)
ensures forall x {:trigger (x%2) }:: x in arr[..] && (x%2==0)==> x in evenNumbers[..]
ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..]
ensures forall k :: 0 <= k < evenNumbers.Length ==> evenNumbers[k] % 2 == 0
ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==>
exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m]
{
var evenList: seq<int> := [];
ghost var indices: seq<int> := [];
for i := 0 to arr.Length
invariant 0 <= i <= arr.Length
invariant 0 <= |evenList| <= i
invariant forall x {:trigger (x%2) }:: (x in arr[..i] && (x%2==0) )==> x in evenList[..]
invariant forall k :: 0 <= k < |evenList| ==> evenList[k] % 2 == 0
invariant forall x :: x !in arr[..i] ==> x !in evenList
invariant |evenList| == |indices|
invariant forall k :: 0 <= k < |indices| ==> indices[k] < i
invariant forall k, l :: 0 <= k < l < |indices| ==> indices[k] < indices[l]
invariant forall k :: 0 <= k < |evenList| ==> 0 <= indices[k] < i <= arr.Length && arr[indices[k]] == evenList[k]
{
if arr[i]%2==0
{
evenList := evenList + [arr[i]];
indices := indices + [i];
}
}
evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]);
assert evenList == evenNumbers[..];
}
|
Clover_even_list.dfy
|
041
|
041
|
Dafny program: 041
|
method Find(a: array<int>, key: int) returns (index: int)
ensures -1<=index<a.Length
ensures index!=-1 ==> a[index]==key && (forall i :: 0 <= i < index ==> a[i] != key)
ensures index == -1 ==> (forall i::0 <= i < a.Length ==> a[i] != key)
{
index := 0;
while index < a.Length
{
if a[index] == key { return; }
index := index + 1;
}
if index >= a.Length {
index := -1;
}
}
|
method Find(a: array<int>, key: int) returns (index: int)
ensures -1<=index<a.Length
ensures index!=-1 ==> a[index]==key && (forall i :: 0 <= i < index ==> a[i] != key)
ensures index == -1 ==> (forall i::0 <= i < a.Length ==> a[i] != key)
{
index := 0;
while index < a.Length
invariant 0<=index<=a.Length
invariant (forall i::0 <= i < index==>a[i] != key)
{
if a[index] == key { return; }
index := index + 1;
}
if index >= a.Length {
index := -1;
}
}
|
Clover_find.dfy
|
042
|
042
|
Dafny program: 042
|
method has_close_elements(numbers: seq<real>, threshold: real) returns (res: bool)
requires threshold >= 0.0
ensures res ==> exists i: int, j: int :: 0 <= i < |numbers| && 0 <= j < |numbers| && i != j && (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) < threshold
ensures !res ==> (forall i: int, j: int :: 1 <= i < |numbers| && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold)
{
res := false;
var idx: int := 0;
while idx < |numbers| && !res
{
var idx2: int := 0;
while idx2 < idx && !res
{
var distance := (if numbers[idx2] - numbers[idx] < 0.0 then numbers[idx] - numbers[idx2] else numbers[idx2] - numbers[idx]);
if distance < threshold {
res := true;
return;
}
idx2 := idx2 + 1;
}
idx := idx + 1;
}
}
|
method has_close_elements(numbers: seq<real>, threshold: real) returns (res: bool)
requires threshold >= 0.0
ensures res ==> exists i: int, j: int :: 0 <= i < |numbers| && 0 <= j < |numbers| && i != j && (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) < threshold
ensures !res ==> (forall i: int, j: int :: 1 <= i < |numbers| && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold)
{
res := false;
var idx: int := 0;
while idx < |numbers| && !res
invariant 0 <= idx <= |numbers|
invariant !res
invariant forall i: int, j: int :: 0 <= i < idx && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold
{
var idx2: int := 0;
while idx2 < idx && !res
invariant 0 <= idx <= |numbers|
invariant 0 <= idx2 <= idx
invariant !res
invariant forall j: int :: 0 <= j < idx2 ==> (if numbers[idx] - numbers[j] < 0.0 then numbers[j] - numbers[idx] else numbers[idx] - numbers[j]) >= threshold
{
var distance := (if numbers[idx2] - numbers[idx] < 0.0 then numbers[idx] - numbers[idx2] else numbers[idx2] - numbers[idx]);
if distance < threshold {
res := true;
return;
}
idx2 := idx2 + 1;
}
idx := idx + 1;
}
}
|
Clover_has_close_elements.dfy
|
043
|
043
|
Dafny program: 043
|
method insert(line:array<char>, l:int, nl:array<char>, p:int, at:int)
requires 0 <= l+p <= line.Length
requires 0 <= p <= nl.Length
requires 0 <= at <= l
modifies line
ensures forall i :: (0<=i<p) ==> line[at+i] == nl[i]
ensures forall i :: (0<=i<at) ==> line[i] == old(line[i])
ensures forall i :: (at+p<=i<l+p) ==> line[i] == old(line[i-p])
{
ghost var initialLine := line[..];
var i:int := l;
while(i>at)
{
i := i - 1;
line[i+p] := line[i];
}
i := 0;
while(i<p)
{
line[at + i] := nl[i];
i := i + 1;
}
}
|
method insert(line:array<char>, l:int, nl:array<char>, p:int, at:int)
requires 0 <= l+p <= line.Length
requires 0 <= p <= nl.Length
requires 0 <= at <= l
modifies line
ensures forall i :: (0<=i<p) ==> line[at+i] == nl[i]
ensures forall i :: (0<=i<at) ==> line[i] == old(line[i])
ensures forall i :: (at+p<=i<l+p) ==> line[i] == old(line[i-p])
{
ghost var initialLine := line[..];
var i:int := l;
while(i>at)
invariant line[0..i] == initialLine[0..i]
invariant line[i+p..l+p] == initialLine[i..l]
invariant at<=i<=l
{
i := i - 1;
line[i+p] := line[i];
}
assert line[0..at] == initialLine[0..at];
assert line[at+p..l+p] == initialLine[at..l];
i := 0;
while(i<p)
invariant 0<=i<=p
invariant line[0..at] == initialLine[0..at]
invariant line[at..at+i] == nl[0..i]
invariant line[at+p..l+p] == initialLine[at..l]
{
line[at + i] := nl[i];
i := i + 1;
}
assert line[0..at] == initialLine[0..at];
assert line[at..at+p] == nl[0..p];
assert line[at+p..l+p] == initialLine[at..l];
}
|
Clover_insert.dfy
|
044
|
044
|
Dafny program: 044
|
method SquareRoot(N:nat) returns (r:nat)
ensures r*r <= N < (r+1)*(r+1)
{
r:=0;
while (r+1)*(r+1)<=N
{
r:=r+1;
}
}
|
method SquareRoot(N:nat) returns (r:nat)
ensures r*r <= N < (r+1)*(r+1)
{
r:=0;
while (r+1)*(r+1)<=N
invariant r*r<=N
{
r:=r+1;
}
}
|
Clover_integer_square_root.dfy
|
046
|
046
|
Dafny program: 046
|
method IsPalindrome(x: seq<char>) returns (result: bool)
ensures result <==> (forall i :: 0 <= i < |x| ==> x[i] == x[|x| - i - 1])
{
if |x|==0 {
return true;
}
var i := 0;
var j := |x| - 1;
result := true;
while (i < j)
{
if x[i] != x[j] {
result := false;
return;
}
i := i + 1;
j := j - 1;
}
}
|
method IsPalindrome(x: seq<char>) returns (result: bool)
ensures result <==> (forall i :: 0 <= i < |x| ==> x[i] == x[|x| - i - 1])
{
if |x|==0 {
return true;
}
var i := 0;
var j := |x| - 1;
result := true;
while (i < j)
invariant 0<=i<=j+1 && 0<=j < |x|
invariant i+j==|x|-1
invariant (forall k :: 0 <= k < i ==> x[k] == x[|x| - k - 1])
{
if x[i] != x[j] {
result := false;
return;
}
i := i + 1;
j := j - 1;
}
}
|
Clover_is_palindrome.dfy
|
047
|
047
|
Dafny program: 047
|
method LinearSearch(a: array<int>, e: int) returns (n:int)
ensures 0<=n<=a.Length
ensures n==a.Length || a[n]==e
ensures forall i::0<=i < n ==> e!=a[i]
{
n :=0;
while n!=a.Length
{
if e==a[n]{
return;
}
n:=n+1;
}
}
|
method LinearSearch(a: array<int>, e: int) returns (n:int)
ensures 0<=n<=a.Length
ensures n==a.Length || a[n]==e
ensures forall i::0<=i < n ==> e!=a[i]
{
n :=0;
while n!=a.Length
invariant 0<=n<=a.Length
invariant forall i::0<=i<n ==> e!=a[i]
{
if e==a[n]{
return;
}
n:=n+1;
}
}
|
Clover_linear_search1.dfy
|
048
|
048
|
Dafny program: 048
|
method LinearSearch(a: array<int>, e: int) returns (n:int)
requires exists i::0<=i<a.Length && a[i]==e
ensures 0<=n<a.Length && a[n]==e
ensures forall k :: 0 <= k < n ==> a[k]!=e
{
n :=0;
while n!=a.Length
{
if e==a[n]{
return;
}
n:=n+1;
}
}
|
method LinearSearch(a: array<int>, e: int) returns (n:int)
requires exists i::0<=i<a.Length && a[i]==e
ensures 0<=n<a.Length && a[n]==e
ensures forall k :: 0 <= k < n ==> a[k]!=e
{
n :=0;
while n!=a.Length
invariant 0<=n<=a.Length
invariant forall i::0<=i<n ==> e!=a[i]
{
if e==a[n]{
return;
}
n:=n+1;
}
}
|
Clover_linear_search2.dfy
|
049
|
049
|
Dafny program: 049
|
method LinearSearch3<T>(a: array<T>, P: T -> bool) returns (n: int)
requires exists i :: 0 <= i < a.Length && P(a[i])
ensures 0 <= n < a.Length && P(a[n])
ensures forall k :: 0 <= k < n ==> !P(a[k])
{
n := 0;
while true
{
if P(a[n]) {
return;
}
n := n + 1;
}
}
|
method LinearSearch3<T>(a: array<T>, P: T -> bool) returns (n: int)
requires exists i :: 0 <= i < a.Length && P(a[i])
ensures 0 <= n < a.Length && P(a[n])
ensures forall k :: 0 <= k < n ==> !P(a[k])
{
n := 0;
while true
invariant 0 <= n < a.Length
invariant exists i :: n <= i < a.Length && P(a[i])
invariant forall k :: 0 <= k < n ==> !P(a[k])
decreases a.Length - n
{
if P(a[n]) {
return;
}
n := n + 1;
}
}
|
Clover_linear_search3.dfy
|
050
|
050
|
Dafny program: 050
|
method LongestCommonPrefix(str1: seq<char>, str2: seq<char>) returns (prefix: seq<char>)
ensures |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|]
ensures |prefix|==|str1| || |prefix|==|str2| || (str1[|prefix|]!=str2[|prefix|])
{
prefix := [];
var minLength := if |str1| <|str2| then |str1| else |str2|;
for idx:= 0 to minLength
{
if str1[idx] != str2[idx] {
return;
}
prefix := prefix + [str1[idx]];
}
}
|
method LongestCommonPrefix(str1: seq<char>, str2: seq<char>) returns (prefix: seq<char>)
ensures |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|]
ensures |prefix|==|str1| || |prefix|==|str2| || (str1[|prefix|]!=str2[|prefix|])
{
prefix := [];
var minLength := if |str1| <|str2| then |str1| else |str2|;
for idx:= 0 to minLength
invariant |prefix|==idx <= minLength<=|str1| && minLength<=|str2|
invariant |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|]
{
if str1[idx] != str2[idx] {
return;
}
prefix := prefix + [str1[idx]];
}
}
|
Clover_longest_prefix.dfy
|
051
|
051
|
Dafny program: 051
|
method Match(s: string, p: string) returns (b: bool)
requires |s| == |p|
ensures b <==> forall n :: 0 <= n < |s| ==> s[n] == p[n] || p[n] == '?'
{
var i := 0;
while i < |s|
{
if s[i] != p[i] && p[i] != '?'
{
return false;
}
i := i + 1;
}
return true;
}
|
method Match(s: string, p: string) returns (b: bool)
requires |s| == |p|
ensures b <==> forall n :: 0 <= n < |s| ==> s[n] == p[n] || p[n] == '?'
{
var i := 0;
while i < |s|
invariant 0 <= i <= |s|
invariant forall n :: 0 <= n < i ==> s[n] == p[n] || p[n] == '?'
{
if s[i] != p[i] && p[i] != '?'
{
return false;
}
i := i + 1;
}
return true;
}
|
Clover_match.dfy
|
052
|
052
|
Dafny program: 052
|
method maxArray(a: array<int>) returns (m: int)
requires a.Length >= 1
ensures forall k :: 0 <= k < a.Length ==> m >= a[k]
ensures exists k :: 0 <= k < a.Length && m == a[k]
{
m := a[0];
var index := 1;
while (index < a.Length)
{
m := if m>a[index] then m else a[index];
index := index + 1;
}
}
|
method maxArray(a: array<int>) returns (m: int)
requires a.Length >= 1
ensures forall k :: 0 <= k < a.Length ==> m >= a[k]
ensures exists k :: 0 <= k < a.Length && m == a[k]
{
m := a[0];
var index := 1;
while (index < a.Length)
invariant 0 <= index <= a.Length
invariant forall k :: 0 <= k < index ==> m >= a[k]
invariant exists k :: 0 <= k < index && m == a[k]
decreases a.Length - index
{
m := if m>a[index] then m else a[index];
index := index + 1;
}
}
|
Clover_max_array.dfy
|
053
|
053
|
Dafny program: 053
|
method minArray(a: array<int>) returns (r:int)
requires a.Length > 0
ensures forall i :: 0 <= i < a.Length ==> r <= a[i]
ensures exists i :: 0 <= i < a.Length && r == a[i]
{
r:=a[0];
var i:=1;
while i<a.Length
{
if r>a[i]{
r:=a[i];
}
i:=i+1;
}
}
|
method minArray(a: array<int>) returns (r:int)
requires a.Length > 0
ensures forall i :: 0 <= i < a.Length ==> r <= a[i]
ensures exists i :: 0 <= i < a.Length && r == a[i]
{
r:=a[0];
var i:=1;
while i<a.Length
invariant 0 <= i <= a.Length
invariant forall x :: 0 <= x < i ==> r <= a[x]
invariant exists x :: 0 <= x < i && r == a[x]
{
if r>a[i]{
r:=a[i];
}
i:=i+1;
}
}
|
Clover_min_array.dfy
|
057
|
057
|
Dafny program: 057
|
method onlineMax(a: array<int>, x: int) returns (ghost m:int, p:int)
requires 1<=x<a.Length
requires a.Length!=0
ensures x<=p<a.Length
ensures forall i::0<=i<x==> a[i]<=m
ensures exists i::0<=i<x && a[i]==m
ensures x<=p<a.Length-1 ==> (forall i::0<=i<p ==> a[i]<a[p])
ensures (forall i::x<=i<a.Length && a[i]<=m) ==> p==a.Length-1
{
p:= 0;
var best := a[0];
var i:=1;
while i<x
{
if a[i]>best{
best:=a[i];
}
i:=i+1;
}
m:=best;
i:=x;
while i<a.Length
{
if a[i]>best{
p:=i;
return;
}
i:=i+1;
}
p:=a.Length-1;
}
|
method onlineMax(a: array<int>, x: int) returns (ghost m:int, p:int)
requires 1<=x<a.Length
requires a.Length!=0
ensures x<=p<a.Length
ensures forall i::0<=i<x==> a[i]<=m
ensures exists i::0<=i<x && a[i]==m
ensures x<=p<a.Length-1 ==> (forall i::0<=i<p ==> a[i]<a[p])
ensures (forall i::x<=i<a.Length && a[i]<=m) ==> p==a.Length-1
{
p:= 0;
var best := a[0];
var i:=1;
while i<x
invariant 0<=i<=x
invariant forall j::0<=j<i==> a[j]<=best
invariant exists j::0<=j<i && a[j]==best
{
if a[i]>best{
best:=a[i];
}
i:=i+1;
}
m:=best;
i:=x;
while i<a.Length
invariant x<=i<=a.Length
invariant forall j::x<=j<i ==> a[j]<=m
{
if a[i]>best{
p:=i;
return;
}
i:=i+1;
}
p:=a.Length-1;
}
|
Clover_online_max.dfy
|
058
|
058
|
Dafny program: 058
|
method only_once<T(==)>(a: array<T>, key: T) returns (b:bool)
ensures (multiset(a[..])[key] ==1 ) <==> b
{
var i := 0;
b := false;
var keyCount := 0;
while i < a.Length
{
if (a[i] == key)
{
keyCount := keyCount + 1;
}
if (keyCount == 1)
{ b := true; }
else
{ b := false; }
i := i + 1;
}
}
|
method only_once<T(==)>(a: array<T>, key: T) returns (b:bool)
ensures (multiset(a[..])[key] ==1 ) <==> b
{
var i := 0;
b := false;
var keyCount := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant multiset(a[..i])[key] == keyCount
invariant b <==> (keyCount == 1)
{
if (a[i] == key)
{
keyCount := keyCount + 1;
}
if (keyCount == 1)
{ b := true; }
else
{ b := false; }
i := i + 1;
}
assert a[..a.Length] == a[..];
}
|
Clover_only_once.dfy
|
059
|
059
|
Dafny program: 059
|
method Quotient(x: nat, y:nat) returns (r:int, q:int)
requires y != 0
ensures q * y + r == x && 0 <= r < y && 0 <= q
{
r:=x;
q:=0;
while y<=r
{
r:=r-y;
q:=q+1;
}
}
|
method Quotient(x: nat, y:nat) returns (r:int, q:int)
requires y != 0
ensures q * y + r == x && 0 <= r < y && 0 <= q
{
r:=x;
q:=0;
while y<=r
invariant q*y+r==x && r>=0
decreases r
{
r:=r-y;
q:=q+1;
}
}
|
Clover_quotient.dfy
|
060
|
060
|
Dafny program: 060
|
method remove_front(a:array<int>) returns (c:array<int>)
requires a.Length>0
ensures a[1..] == c[..]
{
c := new int[a.Length-1];
var i:= 1;
while (i < a.Length)
{
c[i-1] := a[i];
i:=i+1;
}
}
|
method remove_front(a:array<int>) returns (c:array<int>)
requires a.Length>0
ensures a[1..] == c[..]
{
c := new int[a.Length-1];
var i:= 1;
while (i < a.Length)
invariant 1 <= i <= a.Length
invariant forall ii::1<=ii<i ==> c[ii-1]==a[ii]
{
c[i-1] := a[i];
i:=i+1;
}
}
|
Clover_remove_front.dfy
|
061
|
061
|
Dafny program: 061
|
method replace(arr: array<int>, k: int)
modifies arr
ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) > k ==> arr[i] == -1
ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) <= k ==> arr[i] == old(arr[i])
{
var i := 0;
while i < arr.Length
{
if arr[i] > k {
arr[i] := -1;
}
i := i + 1;
}
}
|
method replace(arr: array<int>, k: int)
modifies arr
ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) > k ==> arr[i] == -1
ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) <= k ==> arr[i] == old(arr[i])
{
var i := 0;
while i < arr.Length
decreases arr.Length - i
invariant 0 <= i <= arr.Length
invariant forall j :: 0 <= j < i ==> old(arr[j]) > k ==> arr[j] == -1
invariant forall j :: 0 <= j < i ==> old(arr[j]) <= k ==> arr[j] == old(arr[j])
invariant forall j :: i <= j < arr.Length ==> old(arr[j]) == arr[j]
{
if arr[i] > k {
arr[i] := -1;
}
i := i + 1;
}
}
|
Clover_replace.dfy
|
063
|
063
|
Dafny program: 063
|
method reverse(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[a.Length - 1 - i])
{
var i := 0;
while i <a.Length / 2
{
a[i], a[a.Length-1-i] := a[a.Length-1-i], a[i];
i := i + 1;
}
}
|
method reverse(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[a.Length - 1 - i])
{
var i := 0;
while i <a.Length / 2
invariant 0 <= i <= a.Length/2
invariant forall k :: 0 <= k < i || a.Length-1-i < k <= a.Length-1 ==> a[k] == old(a[a.Length-1-k])
invariant forall k :: i <= k <= a.Length-1-i ==> a[k] == old(a[k])
{
a[i], a[a.Length-1-i] := a[a.Length-1-i], a[i];
i := i + 1;
}
}
|
Clover_reverse.dfy
|
064
|
064
|
Dafny program: 064
|
method rotate(a: array<int>, offset:int) returns (b: array<int> )
requires 0<=offset
ensures b.Length==a.Length
ensures forall i::0<=i<a.Length ==> b[i]==a[(i+offset)%a.Length]
{
b:= new int[a.Length];
var i:=0;
while i<a.Length
{
b[i]:=a[(i+offset)%a.Length];
i:=i+1;
}
}
|
method rotate(a: array<int>, offset:int) returns (b: array<int> )
requires 0<=offset
ensures b.Length==a.Length
ensures forall i::0<=i<a.Length ==> b[i]==a[(i+offset)%a.Length]
{
b:= new int[a.Length];
var i:=0;
while i<a.Length
invariant 0<=i<=a.Length
invariant forall j ::0<=j<i ==> b[j]==a[(j+offset)%a.Length]
{
b[i]:=a[(i+offset)%a.Length];
i:=i+1;
}
}
|
Clover_rotate.dfy
|
065
|
065
|
Dafny program: 065
|
method SelectionSort(a: array<int>)
modifies a
ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
ensures multiset(a[..]) == old(multiset(a[..]))
{
var n:= 0;
while n != a.Length
{
var mindex, m := n, n+1;
while m != a.Length
{
if a[m] < a[mindex] {
mindex := m;
}
m := m+1;
}
a[n], a[mindex] := a[mindex], a[n];
n := n+1;
}
}
|
method SelectionSort(a: array<int>)
modifies a
ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
ensures multiset(a[..]) == old(multiset(a[..]))
{
var n:= 0;
while n != a.Length
invariant 0 <= n <= a.Length
invariant forall i, j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]
invariant forall i,j :: 0 <= i < j < n ==> a[i] <= a[j]
invariant multiset(a[..]) == old(multiset(a[..]))
{
var mindex, m := n, n+1;
while m != a.Length
invariant n <= mindex < m <= a.Length
invariant forall i :: n <= i < m ==> a[mindex] <= a[i]
{
if a[m] < a[mindex] {
mindex := m;
}
m := m+1;
}
a[n], a[mindex] := a[mindex], a[n];
n := n+1;
}
}
|
Clover_selectionsort.dfy
|
067
|
067
|
Dafny program: 067
|
method SetToSeq<T>(s: set<T>) returns (xs: seq<T>)
ensures multiset(s) == multiset(xs)
{
xs := [];
var left: set<T> := s;
while left != {}
{
var x :| x in left;
left := left - {x};
xs := xs + [x];
}
}
|
method SetToSeq<T>(s: set<T>) returns (xs: seq<T>)
ensures multiset(s) == multiset(xs)
{
xs := [];
var left: set<T> := s;
while left != {}
invariant multiset(left) + multiset(xs) == multiset(s)
{
var x :| x in left;
left := left - {x};
xs := xs + [x];
}
}
|
Clover_set_to_seq.dfy
|
068
|
068
|
Dafny program: 068
|
method SlopeSearch(a: array2<int>, key: int) returns (m:int, n:int)
requires forall i,j,j'::0<=i<a.Length0 && 0<=j<j'<a.Length1 ==> a[i,j]<=a[i,j']
requires forall i,i',j::0<=i<i'<a.Length0 && 0<=j<a.Length1 ==> a[i,j]<=a[i',j]
requires exists i,j :: 0<=i<a.Length0 && 0<=j<a.Length1 && a[i,j]==key
ensures 0<=m<a.Length0 && 0<=n<a.Length1
ensures a[m,n]==key
{
m,n:=0, a.Length1-1;
while a[m,n] !=key
{
if a[m,n] < key {
m:=m+1;
}else{
n:=n-1;
}
}
}
|
method SlopeSearch(a: array2<int>, key: int) returns (m:int, n:int)
requires forall i,j,j'::0<=i<a.Length0 && 0<=j<j'<a.Length1 ==> a[i,j]<=a[i,j']
requires forall i,i',j::0<=i<i'<a.Length0 && 0<=j<a.Length1 ==> a[i,j]<=a[i',j]
requires exists i,j :: 0<=i<a.Length0 && 0<=j<a.Length1 && a[i,j]==key
ensures 0<=m<a.Length0 && 0<=n<a.Length1
ensures a[m,n]==key
{
m,n:=0, a.Length1-1;
while a[m,n] !=key
invariant 0<=m<a.Length0 && 0<=n<a.Length1
invariant exists i,j :: m<=i<a.Length0 && 0<=j<=n && a[i,j]==key
decreases a.Length0-m+n
{
if a[m,n] < key {
m:=m+1;
}else{
n:=n-1;
}
}
}
|
Clover_slope_search.dfy
|
079
|
079
|
Dafny program: 079
|
method twoSum(nums: array<int>, target: int) returns (i: int, j: int)
requires nums.Length > 1
requires exists i,j::0 <= i < j < nums.Length && nums[i] + nums[j] == target
ensures 0 <= i < j < nums.Length && nums[i] + nums[j] == target
ensures forall ii,jj:: (0 <= ii < i && ii < jj < nums.Length) ==> nums[ii] + nums[jj] != target
ensures forall jj:: i < jj < j ==> nums[i] + nums[jj] != target
{
var n := nums.Length;
i := 0;
j := 1;
while i < n - 1
{
j := i + 1;
while j < n
{
if nums[i] + nums[j] == target {
return;
}
j := j + 1;
}
i := i + 1;
}
}
|
method twoSum(nums: array<int>, target: int) returns (i: int, j: int)
requires nums.Length > 1
requires exists i,j::0 <= i < j < nums.Length && nums[i] + nums[j] == target
ensures 0 <= i < j < nums.Length && nums[i] + nums[j] == target
ensures forall ii,jj:: (0 <= ii < i && ii < jj < nums.Length) ==> nums[ii] + nums[jj] != target
ensures forall jj:: i < jj < j ==> nums[i] + nums[jj] != target
{
var n := nums.Length;
i := 0;
j := 1;
while i < n - 1
invariant 0 <= i < j <= n
invariant forall ii, jj :: 0 <= ii < i && ii < jj < n ==> nums[ii] + nums[jj] != target
{
j := i + 1;
while j < n
invariant 0 <= i < j <= n
invariant forall jj :: i < jj < j ==> nums[i] + nums[jj] != target
{
if nums[i] + nums[j] == target {
return;
}
j := j + 1;
}
i := i + 1;
}
}
|
Clover_two_sum.dfy
|
082
|
082
|
Dafny program: 082
|
// Redo for exam
function gcd(a: nat, b: nat): nat
lemma r1(a: nat)
ensures gcd(a, 0) == a
lemma r2(a:nat)
ensures gcd(a, a) == a
lemma r3(a: nat, b: nat)
ensures gcd(a, b) == gcd(b, a)
lemma r4 (a: nat, b: nat)
ensures b > 0 ==> gcd(a, b) == gcd(b, a % b)
method GCD1(a: int, b: int) returns (r: int)
requires a > 0 && b > 0
ensures gcd(a,b) == r
{
if a < b {
r3(a,b);
r := GCD1(b, a);
} else if (a % b == 0) {
r4(a,b);
r1(b);
r := b;
} else {
r4(a,b);
r := GCD1(b, a % b);
}
}
method GCD2(a: int, b: int) returns (r: int)
requires a > 0 && b >= 0
ensures gcd(a,b) == r
{
r1(a);
r4(a,b);
( b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a) )
&&
( (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))) );
b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a);
b == 0 ==> a > 0 && b >= 0 && gcd(a,b) == a;
(b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)));
b >= 0 && b != 0 ==> b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));
if b == 0 {
r1(a);
gcd(a,b) == a;
r := a;
gcd(a,b) == r;
} else {
r4(a,b);
// Method call rule
b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));
// assert
// gcd(a,b) == GCD2(b, a % b);
r := GCD2(b, a % b);
gcd(a,b) == r;
}
gcd(a,b) == r;
}
|
// Redo for exam
function gcd(a: nat, b: nat): nat
lemma r1(a: nat)
ensures gcd(a, 0) == a
lemma r2(a:nat)
ensures gcd(a, a) == a
lemma r3(a: nat, b: nat)
ensures gcd(a, b) == gcd(b, a)
lemma r4 (a: nat, b: nat)
ensures b > 0 ==> gcd(a, b) == gcd(b, a % b)
method GCD1(a: int, b: int) returns (r: int)
requires a > 0 && b > 0
ensures gcd(a,b) == r
decreases b
{
if a < b {
r3(a,b);
r := GCD1(b, a);
} else if (a % b == 0) {
r4(a,b);
assert b > 0;
assert gcd(a, b) == gcd(b, a % b);
assert a % b == 0;
assert gcd(a, b) == gcd(b, 0);
r1(b);
assert gcd(a, b) == b;
r := b;
assert gcd(a,b) == r;
} else {
r4(a,b);
r := GCD1(b, a % b);
assert gcd(a,b) == r;
}
assert gcd(a,b) == r;
}
method GCD2(a: int, b: int) returns (r: int)
requires a > 0 && b >= 0
decreases b
ensures gcd(a,b) == r
{
r1(a);
r4(a,b);
assert
( b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a) )
&&
( (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))) );
assert
b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a);
assert
b == 0 ==> a > 0 && b >= 0 && gcd(a,b) == a;
assert
(b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)));
assert
b >= 0 && b != 0 ==> b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));
if b == 0 {
r1(a);
assert
gcd(a,b) == a;
r := a;
assert
gcd(a,b) == r;
} else {
r4(a,b);
// Method call rule
assert
b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));
// assert
// gcd(a,b) == GCD2(b, a % b);
r := GCD2(b, a % b);
assert
gcd(a,b) == r;
}
assert
gcd(a,b) == r;
}
|
Correctness_tmp_tmpwqvg5q_4_HoareLogic_exam.dfy
|
083
|
083
|
Dafny program: 083
|
/**
(a) Verify whether or not the following program
satisfies total correctness.
You should use weakest precondition reasoning
and may extend the loop invariant if required.
You will need to add a decreases clause to prove termination
(a) Weakest precondition proof (without termination) (6 marks)
Termination proof (2marks)
*/
function fusc(n: int): nat
lemma rule1()
ensures fusc(0) == 0
lemma rule2()
ensures fusc(1) == 1
lemma rule3(n:nat)
ensures fusc(2*n) == fusc(n)
lemma rule4(n:nat)
ensures fusc(2*n+1) == fusc(n) + fusc(n+1)
method ComputeFusc(N: int) returns (b: int)
requires N >= 0
ensures b == fusc(N)
{
b := 0;
var n, a := N, 1;
while (n != 0)
{
ghost var d := n; // termination metric
if (n % 2 == 0)
{
rule4(n/2);
rule3(n/2);
a := a + b;
n := n / 2;
} else {
rule4((n-1)/2);
rule3((n-1)/2);
rule3((n+1)/2);
b * fusc(n) - b * fusc(n) + b * fusc(((n-1)/2)+1) + a * fusc(n);
b * fusc(n) - b * (fusc(n) - fusc(((n-1)/2)+1)) + a * fusc(n);
a * fusc(n - 1) + b * fusc(n) - b * fusc(n-1) + a * fusc(n) - a * fusc(n-1);
b := b + a;
n := (n - 1) / 2;
}
}
rule1();
rule2();
}
|
/**
(a) Verify whether or not the following program
satisfies total correctness.
You should use weakest precondition reasoning
and may extend the loop invariant if required.
You will need to add a decreases clause to prove termination
(a) Weakest precondition proof (without termination) (6 marks)
Termination proof (2marks)
*/
function fusc(n: int): nat
lemma rule1()
ensures fusc(0) == 0
lemma rule2()
ensures fusc(1) == 1
lemma rule3(n:nat)
ensures fusc(2*n) == fusc(n)
lemma rule4(n:nat)
ensures fusc(2*n+1) == fusc(n) + fusc(n+1)
method ComputeFusc(N: int) returns (b: int)
requires N >= 0
ensures b == fusc(N)
{
b := 0;
var n, a := N, 1;
assert 0 <= n <= N;
assert fusc(N) == a * fusc(n) + b * fusc(n + 1);
while (n != 0)
invariant 0 <= n <= N // J
invariant fusc(N) == a * fusc(n) + b * fusc(n + 1) // J
decreases n // D
{
ghost var d := n; // termination metric
assert fusc(N) == a * fusc(n) + b * fusc(n + 1);
assert n != 0;
assert (n % 2 != 0 && n % 2 == 0) || fusc(N) == a * fusc(n) + b * fusc(n + 1);
assert (n % 2 != 0 || n % 2 == 0) ==> fusc(N) == a * fusc(n) + b * fusc(n + 1);
assert n % 2 != 0 || fusc(N) == a * fusc(n) + b * fusc(n + 1);
assert n % 2 == 0 || fusc(N) == a * fusc(n) + b * fusc(n + 1);
assert n % 2 == 0 ==> fusc(N) == a * fusc(n) + b * fusc(n + 1);
assert n % 2 != 0 ==> fusc(N) == a * fusc(n) + b * fusc(n + 1);
if (n % 2 == 0)
{
rule4(n/2);
assert fusc((n/2) + 1) == fusc(n + 1) - fusc(n/2);
rule3(n/2);
assert fusc(n/2) == fusc(n);
assert fusc(N) == (a + b) * fusc(n/2) + b * fusc((n/2) + 1);
a := a + b;
assert fusc(N) == a * fusc(n/2) + b * fusc((n/2) + 1);
n := n / 2;
assert fusc(N) == a * fusc(n) + b * fusc(n + 1);
} else {
rule4((n-1)/2);
assert fusc(n) - fusc((n-1)/2) == fusc(((n-1)/2)+1);
rule3((n-1)/2);
assert fusc((n-1)/2) == fusc(n-1);
assert fusc(((n-1)/2)+1) == fusc((n+1)/2);
rule3((n+1)/2);
assert fusc((n+1)/2) == fusc(n+1);
assert fusc(N) == a * fusc(n) + b * fusc(n + 1);
assert fusc(N) == b * fusc(((n-1)/2)+1) + a * fusc(n);
assert fusc(N) ==
b * fusc(n) - b * fusc(n) + b * fusc(((n-1)/2)+1) + a * fusc(n);
assert fusc(N) ==
b * fusc(n) - b * (fusc(n) - fusc(((n-1)/2)+1)) + a * fusc(n);
assert fusc(N) == b * fusc(n) - b * fusc((n-1)/2) + a * fusc(n);
assert fusc(N) == b * fusc(n) - b * fusc(n-1) + a * fusc(n);
assert fusc(N) == b * fusc(n) - b * fusc(n-1) + a * fusc(n);
assert fusc(N) ==
a * fusc(n - 1) + b * fusc(n) - b * fusc(n-1) + a * fusc(n) - a * fusc(n-1);
assert fusc(N) == a * fusc(n - 1) + (b + a) * (fusc(n) - fusc(n-1));
assert fusc(N) == a * fusc((n - 1)) + (b + a) * (fusc(n) - fusc((n-1)/2));
assert fusc(N) == a * fusc((n - 1) / 2) + (b + a) * fusc(((n - 1) / 2) + 1);
b := b + a;
assert fusc(N) == a * fusc((n - 1) / 2) + b * fusc(((n - 1) / 2) + 1);
n := (n - 1) / 2;
assert fusc(N) == a * fusc(n) + b * fusc(n + 1);
}
assert n < d; // termination metric
assert fusc(N) == a * fusc(n) + b * fusc(n + 1); // J
}
assert n == 0; // !B
rule1();
assert fusc(0) == 0;
rule2();
assert fusc(1) == 1;
assert fusc(N) == a * fusc(0) + b * fusc(0 + 1); // J
assert fusc(N) == a * 0 + b * 1; // J
assert b == fusc(N);
}
|
Correctness_tmp_tmpwqvg5q_4_MethodCalls_q1.dfy
|
084
|
084
|
Dafny program: 084
|
/**
Ather, Mohammad Faiz (s4648481/3)
CSSE3100
Assignemnt 3
The University of Queensland
*/
// Question 1
method Tangent(r: array<int>, x: array<int>)
returns (found: bool)
requires forall i:: 1 <= i < x.Length ==>
x[i-1] < x[i]
requires forall i, j ::
0 <= i < j < x.Length ==>
x[i] < x[j]
ensures !found ==>
forall i,j ::
0 <= i < r.Length &&
0 <= j < x.Length ==>
r[i] != x[j]
ensures found ==>
exists i,j ::
0 <= i < r.Length &&
0 <= j < x.Length &&
r[i] == x[j]
{
found := false;
var n, f := 0, x.Length;
while n != r.Length && !found
forall i,j ::
0 <= i < n &&
0 <= j < x.Length ==>
r[i] != x[j]
exists i,j ::
0 <= i < r.Length &&
0 <= j < x.Length &&
n == i && f == j &&
r[i] == x[j]
{
f := BinarySearch(x, r[n]);
/*
not iterate over either array
once a tangent has been found
*/ // see if
if (f != x.Length && r[n] == x[f]) {
found := true;
} else {
n := n + 1;
}
}
(!found && n == r.Length) ||
( found && n != r.Length && r[n] == x[f]);
!false; // sanity check
}
// Author: Leino, Title: Program Proofs
method BinarySearch(a: array<int>, circle: int)
returns (n: int)
requires forall i ::
1 <= i < a.Length
==> a[i-1] < a[i]
requires forall i, j ::
0 <= i < j < a.Length ==>
a[i] < a[j]
ensures 0 <= n <= a.Length
ensures forall i ::
0 <= i < n ==>
a[i] < circle
ensures forall i ::
n <= i < a.Length ==>
circle <= a[i]
{
var lo, hi := 0, a.Length;
while lo < hi
0 <= i < lo ==>
a[i] < circle
hi <= i < a.Length ==>
a[i] >= circle
{
var mid := (lo + hi) / 2;
calc {
lo;
==
(lo + lo) / 2;
<= { assert lo <= hi; }
(lo + hi) / 2;
< { assert lo < hi; }
(hi + hi) / 2;
==
hi;
}
/*
for a given circle in r,
should not iterate over array x
once it can be deduced that
no tangent will be found for that circle.
*/ // see if and 1st else if
if (a[lo] > circle) {
hi := lo;
} else if (a[hi-1] < circle) {
lo := hi;
} else if (a[mid] < circle) {
lo := mid + 1;
} else {
hi := mid;
}
}
n := lo;
!false; // sanity check
}
|
/**
Ather, Mohammad Faiz (s4648481/3)
CSSE3100
Assignemnt 3
The University of Queensland
*/
// Question 1
method Tangent(r: array<int>, x: array<int>)
returns (found: bool)
requires forall i:: 1 <= i < x.Length ==>
x[i-1] < x[i]
requires forall i, j ::
0 <= i < j < x.Length ==>
x[i] < x[j]
ensures !found ==>
forall i,j ::
0 <= i < r.Length &&
0 <= j < x.Length ==>
r[i] != x[j]
ensures found ==>
exists i,j ::
0 <= i < r.Length &&
0 <= j < x.Length &&
r[i] == x[j]
{
found := false;
var n, f := 0, x.Length;
while n != r.Length && !found
invariant 0 <= n <= r.Length
invariant !found ==>
forall i,j ::
0 <= i < n &&
0 <= j < x.Length ==>
r[i] != x[j]
invariant found ==>
exists i,j ::
0 <= i < r.Length &&
0 <= j < x.Length &&
n == i && f == j &&
r[i] == x[j]
decreases r.Length - n, !found
{
f := BinarySearch(x, r[n]);
/*
not iterate over either array
once a tangent has been found
*/ // see if
if (f != x.Length && r[n] == x[f]) {
found := true;
} else {
n := n + 1;
}
}
assert
(!found && n == r.Length) ||
( found && n != r.Length && r[n] == x[f]);
assert
!false; // sanity check
}
// Author: Leino, Title: Program Proofs
method BinarySearch(a: array<int>, circle: int)
returns (n: int)
requires forall i ::
1 <= i < a.Length
==> a[i-1] < a[i]
requires forall i, j ::
0 <= i < j < a.Length ==>
a[i] < a[j]
ensures 0 <= n <= a.Length
ensures forall i ::
0 <= i < n ==>
a[i] < circle
ensures forall i ::
n <= i < a.Length ==>
circle <= a[i]
{
var lo, hi := 0, a.Length;
while lo < hi
invariant 0 <= lo <= hi <= a.Length
invariant forall i ::
0 <= i < lo ==>
a[i] < circle
invariant forall i ::
hi <= i < a.Length ==>
a[i] >= circle
decreases hi - lo
{
var mid := (lo + hi) / 2;
calc {
lo;
==
(lo + lo) / 2;
<= { assert lo <= hi; }
(lo + hi) / 2;
< { assert lo < hi; }
(hi + hi) / 2;
==
hi;
}
/*
for a given circle in r,
should not iterate over array x
once it can be deduced that
no tangent will be found for that circle.
*/ // see if and 1st else if
if (a[lo] > circle) {
hi := lo;
} else if (a[hi-1] < circle) {
lo := hi;
} else if (a[mid] < circle) {
lo := mid + 1;
} else {
hi := mid;
}
}
n := lo;
assert
!false; // sanity check
}
|
Correctness_tmp_tmpwqvg5q_4_Sorting_Tangent.dfy
|
085
|
085
|
Dafny program: 085
|
//Method barrier below receives an array and an integer p
//and returns a boolean b which is true if and only if
//all the positions to the left of p and including also position p contain elements
//that are strictly smaller than all the elements contained in the positions to the right of p
//Examples:
// If v=[7,2,5,8] and p=0 or p=1 then the method must return false,
// but for p=2 the method should return true
//1.Specify the method
//2.Implement an O(v.size()) method
//3.Verify the method
method barrier(v:array<int>,p:int) returns (b:bool)
//Give the precondition
//Give the postcondition
//{Implement and verify}
requires v.Length > 0
requires 0<=p<v.Length
ensures b==forall k,l::0<=k<=p && p<l<v.Length ==> v[k]<v[l]
{
var i:=1;
var max:=0;
while(i<=p)
{
if(v[i]>v[max]){
max:=i;
}
i:=i+1;
}
while(i<v.Length && v[i]>v[max])
{
i:=i+1;
}
b:=i==v.Length;
}
|
//Method barrier below receives an array and an integer p
//and returns a boolean b which is true if and only if
//all the positions to the left of p and including also position p contain elements
//that are strictly smaller than all the elements contained in the positions to the right of p
//Examples:
// If v=[7,2,5,8] and p=0 or p=1 then the method must return false,
// but for p=2 the method should return true
//1.Specify the method
//2.Implement an O(v.size()) method
//3.Verify the method
method barrier(v:array<int>,p:int) returns (b:bool)
//Give the precondition
//Give the postcondition
//{Implement and verify}
requires v.Length > 0
requires 0<=p<v.Length
ensures b==forall k,l::0<=k<=p && p<l<v.Length ==> v[k]<v[l]
{
var i:=1;
var max:=0;
while(i<=p)
decreases p-i
invariant 0<=i<=p+1
invariant 0<=max<i
invariant forall k::0<=k<i ==> v[max] >= v[k]
{
if(v[i]>v[max]){
max:=i;
}
i:=i+1;
}
while(i<v.Length && v[i]>v[max])
decreases v.Length - i
invariant 0<=i<=v.Length
invariant forall k::0<=k<=p ==> v[k]<=v[max]
invariant forall k::p<k<i ==> v[k] > v[max]
{
i:=i+1;
}
b:=i==v.Length;
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session10Exercises_ExerciseBarrier.dfy
|
087
|
087
|
Dafny program: 087
|
function fib(n: nat): nat
{
if n == 0 then 0 else
if n == 1 then 1 else
fib(n - 1) + fib(n - 2)
}
method fibonacci1(n:nat) returns (f:nat)
ensures f==fib(n)
{
var i := 0;
f := 0;
var fsig := 1;
while i < n
{
f, fsig := fsig, f + fsig;
i := i + 1;
}
}
method fibonacci2(n:nat) returns (f:nat)
ensures f==fib(n)
{
if (n==0) {f:=0;}
else{
var i := 1;
var fant := 0;
f := 1;
while i < n
{
fant, f := f, fant + f;
i := i + 1;
}
}
}
method fibonacci3(n:nat) returns (f:nat)
ensures f==fib(n)
{
{
var i: int := 0;
var a := 1;
f := 0;
while i < n
else a==fib(i-1) && f==fib(i)
{
a, f := f, a + f;
i := i + 1;
}
}
}
|
function fib(n: nat): nat
decreases n
{
if n == 0 then 0 else
if n == 1 then 1 else
fib(n - 1) + fib(n - 2)
}
method fibonacci1(n:nat) returns (f:nat)
ensures f==fib(n)
{
var i := 0;
f := 0;
var fsig := 1;
while i < n
decreases n - i//write the bound
invariant f==fib(i) && fsig==fib(i+1)//write the invariant
invariant i<=n
{
f, fsig := fsig, f + fsig;
i := i + 1;
}
}
method fibonacci2(n:nat) returns (f:nat)
ensures f==fib(n)
{
if (n==0) {f:=0;}
else{
var i := 1;
var fant := 0;
f := 1;
while i < n
decreases n-i//write the bound
invariant fant==fib(i-1) && f==fib(i)//write the invariant
invariant i<=n
{
fant, f := f, fant + f;
i := i + 1;
}
}
}
method fibonacci3(n:nat) returns (f:nat)
ensures f==fib(n)
{
{
var i: int := 0;
var a := 1;
f := 0;
while i < n
decreases n-i//write the bound
invariant 0<=i<=n
invariant if i ==0 then a==fib(i+1) && f==fib(i)//write the invariant
else a==fib(i-1) && f==fib(i)
{
a, f := f, a + f;
i := i + 1;
}
}
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseFibonacci.dfy
|
088
|
088
|
Dafny program: 088
|
predicate positive(s:seq<int>)
{forall u::0<=u<|s| ==> s[u]>=0}
method mpositive(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=0;
//1. assert positive(v[..0])
while i<v.Length && v[i]>=0
{
//2. assert 0<=i<v.Length && positive(v[..i]);
i:=i+1;
//2. assert 0<=i<v.Length && positive(v[..i]);
}
//3. assert i==v.Length ==> positive(v[..]);
//3. assert i<v.Length => v[i]<0;
b := i==v.Length;
}
method mpositive3(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=0; b:=true;
while(i<v.Length && b)
{
b:=v[i]>=0;
i:=i+1;
}
}
method mpositive4(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=0; b:=true;
while(i<v.Length && b)
{
b:=v[i]>=0;
i:=i+1;
}
}
method mpositivertl(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=v.Length-1;
while(i>=0 && v[i]>=0)
{
i:=i-1;
}
b:= i==-1;
}
|
predicate positive(s:seq<int>)
{forall u::0<=u<|s| ==> s[u]>=0}
method mpositive(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=0;
//1. assert positive(v[..0])
while i<v.Length && v[i]>=0
decreases v.Length - i
invariant 0<=i<=v.Length
invariant positive(v[..i])
{
//2. assert 0<=i<v.Length && positive(v[..i]);
i:=i+1;
//2. assert 0<=i<v.Length && positive(v[..i]);
}
//3. assert i==v.Length ==> positive(v[..]);
//3. assert i<v.Length => v[i]<0;
b := i==v.Length;
}
method mpositive3(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=0; b:=true;
while(i<v.Length && b)
decreases v.Length - i
invariant 0 <= i <= v.Length
invariant b==positive(v[0..i])
invariant !b ==> !positive(v[0..v.Length])
{
b:=v[i]>=0;
i:=i+1;
}
}
method mpositive4(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=0; b:=true;
while(i<v.Length && b)
decreases v.Length - i
invariant 0 <= i <= v.Length
invariant b==positive(v[0..i])
invariant !b ==> !positive(v[0..v.Length])
{
b:=v[i]>=0;
i:=i+1;
}
}
method mpositivertl(v:array<int>) returns (b:bool)
ensures b==positive(v[0..v.Length])
{
var i:=v.Length-1;
while(i>=0 && v[i]>=0)
decreases i
invariant -1 <= i < v.Length
invariant positive(v[i+1..])
{
i:=i-1;
}
b:= i==-1;
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExercisePositive.dfy
|
089
|
089
|
Dafny program: 089
|
method mroot1(n:int) returns (r:int) //Cost O(root n)
requires n>=0
ensures r>=0 && r*r <= n <(r+1)*(r+1)
{
r:=0;
while (r+1)*(r+1) <=n
{
r:=r+1;
}
}
method mroot2(n:int) returns (r:int) //Cost O(n)
requires n>=0
ensures r>=0 && r*r <= n <(r+1)*(r+1)
{
r:=n;
while n<r*r
{
r:=r-1;
}
}
method mroot3(n:int) returns (r:int) //Cost O(log n)
requires n>=0
ensures r>=0 && r*r <= n <(r+1)*(r+1)
{ var y:int;
var h:int;
r:=0;
y:=n+1;
//Search in interval [0,n+1)
while (y!=r+1) //[r,y]
{
h:=(r+y)/2;
if (h*h<=n)
{r:=h;}
else
{y:=h;}
}
}
|
method mroot1(n:int) returns (r:int) //Cost O(root n)
requires n>=0
ensures r>=0 && r*r <= n <(r+1)*(r+1)
{
r:=0;
while (r+1)*(r+1) <=n
invariant r>=0 && r*r <=n
decreases n-r*r
{
r:=r+1;
}
}
method mroot2(n:int) returns (r:int) //Cost O(n)
requires n>=0
ensures r>=0 && r*r <= n <(r+1)*(r+1)
{
r:=n;
while n<r*r
invariant 0<=r<=n && n<(r+1)*(r+1)//write the invariant
invariant r*r<=n ==> n<(r+1)*(r+1)
decreases r//write the bound
{
r:=r-1;
}
}
method mroot3(n:int) returns (r:int) //Cost O(log n)
requires n>=0
ensures r>=0 && r*r <= n <(r+1)*(r+1)
{ var y:int;
var h:int;
r:=0;
y:=n+1;
//Search in interval [0,n+1)
while (y!=r+1) //[r,y]
invariant r>=0 && r*r<=n<y*y && y>=r+1// write the invariant
decreases y-r//write the bound
{
h:=(r+y)/2;
if (h*h<=n)
{r:=h;}
else
{y:=h;}
}
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseSquare_root.dfy
|
090
|
090
|
Dafny program: 090
|
//Algorithm 1: From left to right return the first
method mmaximum1(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
{
var j:=1; i:=0;
while(j<v.Length)
{
if(v[j] > v[i]){i:=j;}
j:=j+1;
}
}
//Algorithm 2: From right to left return the last
method mmaximum2(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
{
var j:=v.Length-2; i:=v.Length - 1;
while(j>=0)
{
if(v[j] > v[i]){i:=j;}
j:=j-1;
}
}
method mfirstMaximum(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
ensures forall l:: 0<=l<i ==> v[i]>v[l]
//Algorithm: from left to right
{
var j:=1; i:=0;
while(j<v.Length)
{
if(v[j] > v[i]){i:=j;}
j:=j+1;
}
}
method mlastMaximum(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
ensures forall l:: i<l<v.Length ==> v[i]>v[l]
{
var j:=v.Length-2;
i := v.Length-1;
while(j>=0)
{
if(v[j] > v[i]){i:=j;}
j:=j-1;
}
}
//Algorithm : from left to right
//Algorithm : from right to left
method mmaxvalue1(v:array<int>) returns (m:int)
requires v.Length>0
ensures m in v[..]
ensures forall k::0<=k<v.Length ==> m>=v[k]
{
var i:=mmaximum1(v);
m:=v[i];
}
method mmaxvalue2(v:array<int>) returns (m:int)
requires v.Length>0
ensures m in v[..]
ensures forall k::0<=k<v.Length ==> m>=v[k]
{
var i:=mmaximum2(v);
m:=v[i];
}
|
//Algorithm 1: From left to right return the first
method mmaximum1(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
{
var j:=1; i:=0;
while(j<v.Length)
decreases v.Length - j
invariant 0<=j<=v.Length
invariant 0<=i<j
invariant forall k:: 0<=k<j ==> v[i] >= v[k]
{
if(v[j] > v[i]){i:=j;}
j:=j+1;
}
}
//Algorithm 2: From right to left return the last
method mmaximum2(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
{
var j:=v.Length-2; i:=v.Length - 1;
while(j>=0)
decreases j
invariant 0<=i<v.Length
invariant -1<=j<v.Length-1
invariant forall k :: v.Length>k>j ==> v[k]<=v[i]
{
if(v[j] > v[i]){i:=j;}
j:=j-1;
}
}
method mfirstMaximum(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
ensures forall l:: 0<=l<i ==> v[i]>v[l]
//Algorithm: from left to right
{
var j:=1; i:=0;
while(j<v.Length)
decreases v.Length - j
invariant 0<=j<=v.Length
invariant 0<=i<j
invariant forall k:: 0<=k<j ==> v[i] >= v[k]
invariant forall k:: 0<=k<i ==> v[i] > v[k]
{
if(v[j] > v[i]){i:=j;}
j:=j+1;
}
}
method mlastMaximum(v:array<int>) returns (i:int)
requires v.Length>0
ensures 0<=i<v.Length
ensures forall k:: 0<=k<v.Length ==> v[i]>=v[k]
ensures forall l:: i<l<v.Length ==> v[i]>v[l]
{
var j:=v.Length-2;
i := v.Length-1;
while(j>=0)
decreases j
invariant -1<=j<v.Length-1
invariant 0<=i<v.Length
invariant forall k :: v.Length>k>j ==> v[k]<=v[i]
invariant forall k :: v.Length>k>i ==> v[k]<v[i]
{
if(v[j] > v[i]){i:=j;}
j:=j-1;
}
}
//Algorithm : from left to right
//Algorithm : from right to left
method mmaxvalue1(v:array<int>) returns (m:int)
requires v.Length>0
ensures m in v[..]
ensures forall k::0<=k<v.Length ==> m>=v[k]
{
var i:=mmaximum1(v);
m:=v[i];
}
method mmaxvalue2(v:array<int>) returns (m:int)
requires v.Length>0
ensures m in v[..]
ensures forall k::0<=k<v.Length ==> m>=v[k]
{
var i:=mmaximum2(v);
m:=v[i];
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session3Exercises_ExerciseMaximum.dfy
|
091
|
091
|
Dafny program: 091
|
predicate allEqual(s:seq<int>)
{forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] }
//{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] }
//{forall i::0<i<|s| ==> s[i-1]==s[i]}
//{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]}
//Ordered indexes
lemma equivalenceNoOrder(s:seq<int>)
ensures allEqual(s) <==> forall i,j::0<=i<=j<|s| ==> s[i]==s[j]
{}
//All equal to first
lemma equivalenceEqualtoFirst(s:seq<int>)
requires s!=[]
ensures allEqual(s) <==> (forall i::0<=i<|s| ==> s[0]==s[i])
{}
lemma equivalenceContiguous(s:seq<int>)
ensures (allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1])
ensures (allEqual(s) <== forall i::0<=i<|s|-1 ==> s[i]==s[i+1])
{
if(|s|==0 || |s|==1){
}
else{
calc {
forall i::0<=i<|s|-1 ==> s[i]==s[i+1];
==>
{
equivalenceContiguous(s[..|s|-1]);
}
allEqual(s);
}
}
}
method mallEqual1(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i := 0;
b := true;
while (i < v.Length && b)
{
b:=(v[i]==v[0]);
i := i+1;
}
}
method mallEqual2(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i:int;
b:=true;
i:=0;
while (i < v.Length && v[i] == v[0])
{
i:=i+1;
}
b:=(i==v.Length);
}
method mallEqual3(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
equivalenceContiguous(v[..]);
var i:int;
b:=true;
if (v.Length >0){
i:=0;
while (i<v.Length-1 && v[i]==v[i+1])
{
i:=i+1;
}
b:=(i==v.Length-1);
}
}
method mallEqual4(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i:int;
b:=true;
if (v.Length>0){
i:=0;
while (i < v.Length-1 && b)
{
b:=(v[i]==v[i+1]);
i:=i+1;
}
}
}
method mallEqual5(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i := 0;
b := true;
while (i < v.Length && b)
{
if (v[i] != v[0]) { b := false; }
else { i := i+1;}
}
}
|
predicate allEqual(s:seq<int>)
{forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] }
//{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] }
//{forall i::0<i<|s| ==> s[i-1]==s[i]}
//{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]}
//Ordered indexes
lemma equivalenceNoOrder(s:seq<int>)
ensures allEqual(s) <==> forall i,j::0<=i<=j<|s| ==> s[i]==s[j]
{}
//All equal to first
lemma equivalenceEqualtoFirst(s:seq<int>)
requires s!=[]
ensures allEqual(s) <==> (forall i::0<=i<|s| ==> s[0]==s[i])
{}
lemma equivalenceContiguous(s:seq<int>)
ensures (allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1])
ensures (allEqual(s) <== forall i::0<=i<|s|-1 ==> s[i]==s[i+1])
{
assert allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1];
if(|s|==0 || |s|==1){
}
else{
calc {
forall i::0<=i<|s|-1 ==> s[i]==s[i+1];
==>
{
equivalenceContiguous(s[..|s|-1]);
assert s[|s|-2] == s[|s|-1];
}
allEqual(s);
}
}
}
method mallEqual1(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i := 0;
b := true;
while (i < v.Length && b)
invariant 0 <= i <= v.Length
invariant b==allEqual(v[..i])
decreases v.Length - i
{
b:=(v[i]==v[0]);
i := i+1;
}
}
method mallEqual2(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i:int;
b:=true;
i:=0;
while (i < v.Length && v[i] == v[0])
invariant 0 <= i <= v.Length
invariant forall k:: 0 <= k < i ==> v[k] == v[0]
decreases v.Length - i
{
i:=i+1;
}
b:=(i==v.Length);
}
method mallEqual3(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
equivalenceContiguous(v[..]);
var i:int;
b:=true;
if (v.Length >0){
i:=0;
while (i<v.Length-1 && v[i]==v[i+1])
invariant 0<=i<=v.Length -1
invariant b==allEqual(v[..i+1])
decreases v.Length - i
{
i:=i+1;
}
b:=(i==v.Length-1);
}
}
method mallEqual4(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i:int;
b:=true;
if (v.Length>0){
i:=0;
while (i < v.Length-1 && b)
invariant 0 <= i < v.Length
invariant b==allEqual(v[..i+1])
decreases v.Length - i
{
b:=(v[i]==v[i+1]);
i:=i+1;
}
}
}
method mallEqual5(v:array<int>) returns (b:bool)
ensures b==allEqual(v[0..v.Length])
{
var i := 0;
b := true;
while (i < v.Length && b)
invariant 0<=i<=v.Length//
invariant b ==> forall k::0<=k<i ==> v[k] == v[0]
invariant !b ==> exists k:: 0<=k<v.Length && v[k]!=v[0]
decreases v.Length - i - (if b then 0 else 1)//
{
if (v[i] != v[0]) { b := false; }
else { i := i+1;}
}
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseAllEqual.dfy
|
092
|
092
|
Dafny program: 092
|
predicate strictSorted(s : seq<int>) {
forall u, w :: 0 <= u < w < |s| ==> s[u] < s[w]
}
method mcontained(v:array<int>,w:array<int>,n:int,m:int) returns (b:bool)
//Specify and implement an O(m+n) algorithm that returns b
//v and w are strictly increasing ordered arrays
//b is true iff the first n elements of v are contained in the first m elements of w
requires n<=m && n>=0
requires strictSorted(v[..])
requires strictSorted(w[..])
requires v.Length >= n && w.Length >= m
ensures b==forall k:: 0<= k< n ==> v[k] in w[..m]//exists j :: 0 <= j < m && v[k] == w[j]
{
var i:=0;
var j:=0;
while(i<n && j<m && (v[i] >= w[j])) //&& b)
{
if(v[i] == w[j]){
i:=i+1;
}
j:=j+1;
}
b := i==n;
}
|
predicate strictSorted(s : seq<int>) {
forall u, w :: 0 <= u < w < |s| ==> s[u] < s[w]
}
method mcontained(v:array<int>,w:array<int>,n:int,m:int) returns (b:bool)
//Specify and implement an O(m+n) algorithm that returns b
//v and w are strictly increasing ordered arrays
//b is true iff the first n elements of v are contained in the first m elements of w
requires n<=m && n>=0
requires strictSorted(v[..])
requires strictSorted(w[..])
requires v.Length >= n && w.Length >= m
ensures b==forall k:: 0<= k< n ==> v[k] in w[..m]//exists j :: 0 <= j < m && v[k] == w[j]
{
var i:=0;
var j:=0;
while(i<n && j<m && (v[i] >= w[j])) //&& b)
invariant 0<=i<=n
invariant 0<=j<=m
invariant strictSorted(v[..])
invariant strictSorted(w[..])
invariant forall k::0<=k<i ==> v[k] in w[..j]
invariant i<n ==> !(v[i] in w[..j])
decreases w.Length-j
decreases v.Length-i
{
if(v[i] == w[j]){
i:=i+1;
}
j:=j+1;
}
assert i<n ==> !(v[i] in w[..m]);
b := i==n;
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseContained.dfy
|
093
|
093
|
Dafny program: 093
|
predicate positive(s:seq<int>)
{forall u::0<=u<|s| ==> s[u]>=0}
method mfirstNegative(v:array<int>) returns (b:bool, i:int)
ensures b <==> exists k::0<=k<v.Length && v[k]<0
ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i])
{
i:=0;
b:=false;
while (i<v.Length && !b)
{
b:=(v[i]<0);
i:=i+1;
}
if (b){i:=i-1;}
}
method mfirstNegative2(v:array<int>) returns (b:bool, i:int)
ensures b <==> exists k::0<=k<v.Length && v[k]<0
ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i])
{
i:=0;b:=false;
while (i<v.Length && !b)
{
b:=(v[i]<0);
if (!b) {i:=i+1;}
}
}
|
predicate positive(s:seq<int>)
{forall u::0<=u<|s| ==> s[u]>=0}
method mfirstNegative(v:array<int>) returns (b:bool, i:int)
ensures b <==> exists k::0<=k<v.Length && v[k]<0
ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i])
{
i:=0;
b:=false;
while (i<v.Length && !b)
invariant 0<=i<=v.Length
invariant b <==> exists k::0<=k<i && v[k]<0
invariant b ==> v[i-1]<0 && positive(v[0..i-1])
decreases v.Length - i
{
b:=(v[i]<0);
i:=i+1;
}
if (b){i:=i-1;}
}
method mfirstNegative2(v:array<int>) returns (b:bool, i:int)
ensures b <==> exists k::0<=k<v.Length && v[k]<0
ensures b ==> 0<=i<v.Length && v[i]<0 && positive(v[0..i])
{
i:=0;b:=false;
while (i<v.Length && !b)
invariant 0<=i<=v.Length
invariant b ==> i<v.Length && v[i]<0 && !(exists k::0<=k<i && v[k]<0)
invariant b <== exists k::0<=k<i && v[k]<0
decreases v.Length - i - (if b then 1 else 0)
{
b:=(v[i]<0);
if (!b) {i:=i+1;}
}
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseFirstNegative.dfy
|
094
|
094
|
Dafny program: 094
|
method mfirstCero(v:array<int>) returns (i:int)
ensures 0 <=i<=v.Length
ensures forall j:: 0<=j<i ==> v[j]!=0
ensures i!=v.Length ==> v[i]==0
{
i:=0;
while (i<v.Length && v[i]!=0)
{i:=i+1;}
}
|
method mfirstCero(v:array<int>) returns (i:int)
ensures 0 <=i<=v.Length
ensures forall j:: 0<=j<i ==> v[j]!=0
ensures i!=v.Length ==> v[i]==0
{
i:=0;
while (i<v.Length && v[i]!=0)
invariant 0<=i<=v.Length
invariant forall j:: 0<=j<i ==> v[j]!=0
decreases v.Length -i
{i:=i+1;}
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExercisefirstZero.dfy
|
095
|
095
|
Dafny program: 095
|
function SumR(s:seq<int>):int
{
if (s==[]) then 0
else SumR(s[..|s|-1])+s[|s|-1]
}
function SumL(s:seq<int>):int
{
if (s==[]) then 0
else s[0]+SumL(s[1..])
}
lemma concatLast(s:seq<int>,t:seq<int>)
requires t!=[]
ensures (s+t)[..|s+t|-1] == s+(t[..|t|-1])
{}
lemma concatFirst(s:seq<int>,t:seq<int>)
requires s!=[]
ensures (s+t)[1..] == s[1..]+t
{}
lemma {:induction s,t} SumByPartsR(s:seq<int>,t:seq<int>)
ensures SumR(s+t) == SumR(s)+SumR(t)
{ if (t==[])
{assert s+t == s;}
else if (s==[])
{assert s+t==t;}
else
{
calc =={
SumR(s+t);
SumR((s+t)[..|s+t|-1])+(s+t)[|s+t|-1];
SumR((s+t)[..|s+t|-1])+t[|t|-1];
{concatLast(s,t);}
SumR(s+t[..|t|-1])+t[|t|-1];
{SumByPartsR(s,t[..|t|-1]);}
SumR(s)+SumR(t[..|t|-1])+t[|t|-1];
SumR(s)+SumR(t);
}
}
}
lemma {:induction s,t} SumByPartsL(s:seq<int>,t:seq<int>)
ensures SumL(s+t) == SumL(s)+SumL(t)
//Prove this
{
if(t==[]){
}
else if(s==[]){
}
else{
calc == {
SumL(s+t);
(s+t)[0] + SumL((s+t)[1..]);
s[0] + SumL((s+t)[1..]);
{concatFirst(s,t);}
s[0] + SumL(s[1..] + t);
{SumByPartsL(s[1..], t);}
s[0] + SumL(s[1..]) + SumL(t);
}
}
}
lemma {:induction s,i,j} equalSumR(s:seq<int>,i:int,j:int)
requires 0<=i<=j<=|s|
ensures SumR(s[i..j])==SumL(s[i..j])
//Prove this
{
if(s==[]){
}else{
if(i==j){
}
else{
calc == {
SumR(s[i..j]);
{
}
SumR(s[i..j-1]) + s[j-1];
{equalSumR(s, i, j-1);}
SumL(s[i..j-1]) + s[j-1];
{assert s[j-1] == SumL([s[j-1]]);}
SumL(s[i..j-1]) + SumL([s[j-1]]);
{SumByPartsL(s[i..j-1], [s[j-1]]);}
SumL(s[i..j-1] + [s[j-1]]);
{
}
SumL(s[i..j]);
/*SumR(s[i..j-1])+SumR(s[j..j]);
SumR(s[i..j-1]) + s[j..j];
SumL(s);*/
}
}
}
}
lemma equalSumsV()
ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])
//proving the forall
{ forall v:array<int>,i,j | 0<=i<=j<=v.Length
ensures SumR(v[i..j])==SumL(v[i..j])
{equalSumR(v[..],i,j);}
}
function SumV(v:array<int>,c:int,f:int):int
requires 0<=c<=f<=v.Length
reads v
{SumR(v[c..f])}
lemma ArrayFacts<T>()
ensures forall v : array<T> :: v[..v.Length] == v[..];
ensures forall v : array<T> :: v[0..] == v[..];
ensures forall v : array<T> :: v[0..v.Length] == v[..];
ensures forall v : array<T> ::|v[0..v.Length]|==v.Length;
ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;
ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]
// ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])
{equalSumsV();}
method sumElems(v:array<int>) returns (sum:int)
//ensures sum==SumL(v[0..v.Length])
ensures sum==SumR(v[..])
//ensures sum==SumV(v,0,v.Length)
{ArrayFacts<int>();
sum:=0;
var i:int;
i:=0;
while (i<v.Length)
{
sum:=sum+v[i];
i:=i+1;
}
}
method sumElemsB(v:array<int>) returns (sum:int)
//ensures sum==SumL(v[0..v.Length])
ensures sum==SumR(v[0..v.Length])
{
ArrayFacts<int>();
sum:=0;
var i:int;
i:=v.Length;
equalSumsV();
while(i>0)
{
sum:=sum+v[i-1];
i:=i-1;
}
}
|
function SumR(s:seq<int>):int
decreases s
{
if (s==[]) then 0
else SumR(s[..|s|-1])+s[|s|-1]
}
function SumL(s:seq<int>):int
decreases s
{
if (s==[]) then 0
else s[0]+SumL(s[1..])
}
lemma concatLast(s:seq<int>,t:seq<int>)
requires t!=[]
ensures (s+t)[..|s+t|-1] == s+(t[..|t|-1])
{}
lemma concatFirst(s:seq<int>,t:seq<int>)
requires s!=[]
ensures (s+t)[1..] == s[1..]+t
{}
lemma {:induction s,t} SumByPartsR(s:seq<int>,t:seq<int>)
decreases s,t
ensures SumR(s+t) == SumR(s)+SumR(t)
{ if (t==[])
{assert s+t == s;}
else if (s==[])
{assert s+t==t;}
else
{
calc =={
SumR(s+t);
SumR((s+t)[..|s+t|-1])+(s+t)[|s+t|-1];
SumR((s+t)[..|s+t|-1])+t[|t|-1];
{concatLast(s,t);}
SumR(s+t[..|t|-1])+t[|t|-1];
{SumByPartsR(s,t[..|t|-1]);}
SumR(s)+SumR(t[..|t|-1])+t[|t|-1];
SumR(s)+SumR(t);
}
}
}
lemma {:induction s,t} SumByPartsL(s:seq<int>,t:seq<int>)
decreases s,t
ensures SumL(s+t) == SumL(s)+SumL(t)
//Prove this
{
if(t==[]){
assert s+t==s;
}
else if(s==[]){
assert s+t==t;
}
else{
calc == {
SumL(s+t);
(s+t)[0] + SumL((s+t)[1..]);
s[0] + SumL((s+t)[1..]);
{concatFirst(s,t);}
s[0] + SumL(s[1..] + t);
{SumByPartsL(s[1..], t);}
s[0] + SumL(s[1..]) + SumL(t);
}
}
}
lemma {:induction s,i,j} equalSumR(s:seq<int>,i:int,j:int)
decreases j-i
requires 0<=i<=j<=|s|
ensures SumR(s[i..j])==SumL(s[i..j])
//Prove this
{
if(s==[]){
assert SumR(s) == SumL(s);
}else{
if(i==j){
assert SumR(s[i..j]) == SumL(s[i..j]);
}
else{
calc == {
SumR(s[i..j]);
{
assert s[i..j] == s[i..j-1] + [s[j-1]];
assert SumR(s[i..j]) == SumR(s[i..j-1]) + s[j-1];
}
SumR(s[i..j-1]) + s[j-1];
{equalSumR(s, i, j-1);}
SumL(s[i..j-1]) + s[j-1];
{assert s[j-1] == SumL([s[j-1]]);}
SumL(s[i..j-1]) + SumL([s[j-1]]);
{SumByPartsL(s[i..j-1], [s[j-1]]);}
SumL(s[i..j-1] + [s[j-1]]);
{
assert s[i..j] == s[i..j-1] + [s[j-1]];
}
SumL(s[i..j]);
/*SumR(s[i..j-1])+SumR(s[j..j]);
SumR(s[i..j-1]) + s[j..j];
SumL(s);*/
}
}
}
}
lemma equalSumsV()
ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])
//proving the forall
{ forall v:array<int>,i,j | 0<=i<=j<=v.Length
ensures SumR(v[i..j])==SumL(v[i..j])
{equalSumR(v[..],i,j);}
}
function SumV(v:array<int>,c:int,f:int):int
requires 0<=c<=f<=v.Length
reads v
{SumR(v[c..f])}
lemma ArrayFacts<T>()
ensures forall v : array<T> :: v[..v.Length] == v[..];
ensures forall v : array<T> :: v[0..] == v[..];
ensures forall v : array<T> :: v[0..v.Length] == v[..];
ensures forall v : array<T> ::|v[0..v.Length]|==v.Length;
ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;
ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]
// ensures forall v:array<int>,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])
{equalSumsV();}
method sumElems(v:array<int>) returns (sum:int)
//ensures sum==SumL(v[0..v.Length])
ensures sum==SumR(v[..])
//ensures sum==SumV(v,0,v.Length)
{ArrayFacts<int>();
sum:=0;
var i:int;
i:=0;
while (i<v.Length)
decreases v.Length - i//write
invariant 0<=i<=v.Length && sum == SumR(v[..i])//write
{
sum:=sum+v[i];
i:=i+1;
}
}
method sumElemsB(v:array<int>) returns (sum:int)
//ensures sum==SumL(v[0..v.Length])
ensures sum==SumR(v[0..v.Length])
{
ArrayFacts<int>();
sum:=0;
var i:int;
i:=v.Length;
equalSumsV();
while(i>0)
decreases i//write
invariant 0<=i<=v.Length
invariant sum == SumL(v[i..]) == SumR(v[i..])
{
sum:=sum+v[i-1];
i:=i-1;
}
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session5Exercises_ExerciseSumElems.dfy
|
096
|
096
|
Dafny program: 096
|
predicate positive(s:seq<int>)
{forall u::0<=u<|s| ==> s[u]>=0}
predicate isEven(i:int)
requires i>=0
{i%2==0}
function CountEven(s:seq<int>):int
requires positive(s)
{if s==[] then 0
else (if (s[|s|-1]%2==0) then 1 else 0)+CountEven(s[..|s|-1])
}
lemma ArrayFacts<T>()
ensures forall v : array<T> :: v[..v.Length] == v[..];
ensures forall v : array<T> :: v[0..] == v[..];
ensures forall v : array<T> :: v[0..v.Length] == v[..];
ensures forall v : array<T> ::|v[0..v.Length]|==v.Length;
ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;
ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]
{}
method mcountEven(v:array<int>) returns (n:int)
requires positive(v[..])
ensures n==CountEven(v[..])
{ ArrayFacts<int>();
n:=0;
var i:int;
i:=0;
while (i<v.Length)
{
if (v[i]%2==0) {n:=n+1;}
i:=i+1;
}
}
|
predicate positive(s:seq<int>)
{forall u::0<=u<|s| ==> s[u]>=0}
predicate isEven(i:int)
requires i>=0
{i%2==0}
function CountEven(s:seq<int>):int
decreases s
requires positive(s)
{if s==[] then 0
else (if (s[|s|-1]%2==0) then 1 else 0)+CountEven(s[..|s|-1])
}
lemma ArrayFacts<T>()
ensures forall v : array<T> :: v[..v.Length] == v[..];
ensures forall v : array<T> :: v[0..] == v[..];
ensures forall v : array<T> :: v[0..v.Length] == v[..];
ensures forall v : array<T> ::|v[0..v.Length]|==v.Length;
ensures forall v : array<T> | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;
ensures forall v : array<T> ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]
{}
method mcountEven(v:array<int>) returns (n:int)
requires positive(v[..])
ensures n==CountEven(v[..])
{ ArrayFacts<int>();
n:=0;
var i:int;
i:=0;
while (i<v.Length)
decreases v.Length - i//write
invariant 0<=i<=v.Length//write
invariant n==CountEven(v[..i])
{
if (v[i]%2==0) {n:=n+1;}
i:=i+1;
}
}
|
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExerciseCountEven.dfy
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 18