Dataset Viewer
Auto-converted to Parquet Duplicate
id
int64
name
int64
docstring
string
code
string
ground_truth
string
test_file
string
cv_gt
float64
5
5
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
1.9503
9
9
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
0.2046
10
10
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
1.1843
14
14
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
0.7477
18
18
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
0.7833
19
19
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
0.4938
30
30
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
0.9302
43
43
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
0.4523
65
65
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
0.2738
89
89
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
0.2757
90
90
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
0.3702
91
91
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
0.6251
95
95
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
3.5317
96
96
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
0.2764
98
98
Dafny program: 098
predicate isPeek(v:array<int>,i:int) reads v requires 0<=i<v.Length {forall k::0<=k<i ==> v[i]>=v[k]} function peekSum(v:array<int>,i:int):int reads v requires 0<=i<=v.Length { if (i==0) then 0 else if isPeek(v,i-1) then v[i-1]+peekSum(v,i-1) else peekSum(v,i-1) } method mPeekSum(v:array<int>) returns (sum:int) requires v.Length>0 ensures sum==peekSum(v,v.Length) //Implement and verify an O(v.Length) algorithm to solve this problem { var i:=1; sum:=v[0]; var lmax:=v[0]; while(i<v.Length) { if(v[i]>=lmax){ sum:=sum + v[i]; lmax:=v[i]; } i:=i+1; } }
predicate isPeek(v:array<int>,i:int) reads v requires 0<=i<v.Length {forall k::0<=k<i ==> v[i]>=v[k]} function peekSum(v:array<int>,i:int):int decreases i reads v requires 0<=i<=v.Length { if (i==0) then 0 else if isPeek(v,i-1) then v[i-1]+peekSum(v,i-1) else peekSum(v,i-1) } method mPeekSum(v:array<int>) returns (sum:int) requires v.Length>0 ensures sum==peekSum(v,v.Length) //Implement and verify an O(v.Length) algorithm to solve this problem { var i:=1; sum:=v[0]; var lmax:=v[0]; while(i<v.Length) decreases v.Length -i invariant 0<i<=v.Length invariant lmax in v[..i] invariant forall k::0<=k<i ==> lmax>=v[k]; invariant sum==peekSum(v, i) { if(v[i]>=lmax){ sum:=sum + v[i]; lmax:=v[i]; } i:=i+1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExercisePeekSum.dfy
0.2797
99
99
Dafny program: 099
predicate sorted(s : seq<int>) { forall u, w :: 0 <= u < w < |s| ==> s[u] <= s[w] } method binarySearch(v:array<int>, elem:int) returns (p:int) requires sorted(v[0..v.Length]) ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { var c,f:=0,v.Length-1; while (c<=f) (forall w::f<w<v.Length ==> v[w]>elem) { var m:=(c+f)/2; if (v[m]<=elem) {c:=m+1;} else {f:=m-1;} } p:=c-1; } method search(v:array<int>,elem:int) returns (b:bool) requires sorted(v[0..v.Length]) ensures b==(elem in v[0..v.Length]) //Implement by calling binary search function { var p:=binarySearch(v, elem); if(p==-1){ b:= false; } else{ b:=v[p] == elem; } } //Recursive binary search method {:tailrecursion false} binarySearchRec(v:array<int>, elem:int, c:int, f:int) returns (p:int) requires sorted(v[0..v.Length]) requires 0<=c<=f+1<=v.Length//0<=c<=v.Length && -1<=f<v.Length && c<=f+1 requires forall k::0<=k<c ==> v[k]<=elem requires forall k::f<k<v.Length ==> v[k]>elem ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { if (c==f+1) {p:=c-1;} //empty case: c-1 contains the last element less or equal than elem else { var m:=(c+f)/2; if (v[m]<=elem) {p:=binarySearchRec(v,elem,m+1,f);} else {p:=binarySearchRec(v,elem,c,m-1);} } } method otherbSearch(v:array<int>, elem:int) returns (b:bool,p:int) requires sorted(v[0..v.Length]) ensures 0<=p<=v.Length ensures b == (elem in v[0..v.Length]) ensures b ==> p<v.Length && v[p]==elem ensures !b ==> (forall u::0<=u<p ==> v[u]<elem) && (forall w::p<=w<v.Length ==> v[w]>elem) //Implement and verify { p:=binarySearch(v, elem); if(p==-1){ b:= false; p:=p+1; } else{ b:=v[p] == elem; p:=p + if b then 0 else 1; } }
predicate sorted(s : seq<int>) { forall u, w :: 0 <= u < w < |s| ==> s[u] <= s[w] } method binarySearch(v:array<int>, elem:int) returns (p:int) requires sorted(v[0..v.Length]) ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { var c,f:=0,v.Length-1; while (c<=f) decreases f-c invariant 0<=c<=v.Length && -1<=f<=v.Length-1 && c<=f+1 invariant (forall u::0<=u<c ==> v[u]<=elem) && (forall w::f<w<v.Length ==> v[w]>elem) { var m:=(c+f)/2; if (v[m]<=elem) {c:=m+1;} else {f:=m-1;} } p:=c-1; } method search(v:array<int>,elem:int) returns (b:bool) requires sorted(v[0..v.Length]) ensures b==(elem in v[0..v.Length]) //Implement by calling binary search function { var p:=binarySearch(v, elem); if(p==-1){ b:= false; } else{ b:=v[p] == elem; } } //Recursive binary search method {:tailrecursion false} binarySearchRec(v:array<int>, elem:int, c:int, f:int) returns (p:int) requires sorted(v[0..v.Length]) requires 0<=c<=f+1<=v.Length//0<=c<=v.Length && -1<=f<v.Length && c<=f+1 requires forall k::0<=k<c ==> v[k]<=elem requires forall k::f<k<v.Length ==> v[k]>elem decreases f-c ensures -1<=p<v.Length ensures (forall u::0<=u<=p ==> v[u]<=elem) && (forall w::p<w<v.Length ==> v[w]>elem) { if (c==f+1) {p:=c-1;} //empty case: c-1 contains the last element less or equal than elem else { var m:=(c+f)/2; if (v[m]<=elem) {p:=binarySearchRec(v,elem,m+1,f);} else {p:=binarySearchRec(v,elem,c,m-1);} } } method otherbSearch(v:array<int>, elem:int) returns (b:bool,p:int) requires sorted(v[0..v.Length]) ensures 0<=p<=v.Length ensures b == (elem in v[0..v.Length]) ensures b ==> p<v.Length && v[p]==elem ensures !b ==> (forall u::0<=u<p ==> v[u]<elem) && (forall w::p<=w<v.Length ==> v[w]>elem) //Implement and verify { p:=binarySearch(v, elem); if(p==-1){ b:= false; p:=p+1; } else{ b:=v[p] == elem; p:=p + if b then 0 else 1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBinarySearch.dfy
0.3754
100
100
Dafny program: 100
predicate sorted_seg(a:array<int>, i:int, j:int) //j excluded requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method bubbleSorta(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; while (i< f) { var j:=f-1; while (j > i) { //assert a[j] //assert multiset(a[c..f]) == old(multiset(a[c..f])) ; if (a[j-1]>a[j]){ a[j],a[j-1]:=a[j-1],a[j]; } j:=j-1; } i:=i+1; } } method bubbleSort(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; var b:=true; while (i<f && b) { var j:=f-1; b:=false; while (j>i) { if (a[j-1]>a[j]) { a[j],a[j-1]:=a[j-1],a[j]; b:=true; } j:=j-1; } i:=i+1; } }
predicate sorted_seg(a:array<int>, i:int, j:int) //j excluded requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method bubbleSorta(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; while (i< f) decreases a.Length-i invariant c<=i<=f invariant sorted_seg(a,c,i) invariant forall k,l::c<=k< i && i<=l< f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var j:=f-1; assert multiset(a[c..f]) == old(multiset(a[c..f])) ; while (j > i) decreases j-i//write invariant i <= j<= f-1//write invariant forall k::j<=k<=f-1 ==> a[j] <= a[k] invariant forall k,l::c<=k< i && i<=l< f ==> a[k]<=a[l] invariant sorted_seg(a,c,i) invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { //assert a[j] //assert multiset(a[c..f]) == old(multiset(a[c..f])) ; if (a[j-1]>a[j]){ a[j],a[j-1]:=a[j-1],a[j]; } j:=j-1; } assert sorted_seg(a,c,i+1); assert forall k::i<k<f ==> a[i]<=a[k]; i:=i+1; } } method bubbleSort(a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var i:=c; var b:=true; while (i<f && b) decreases a.Length-i invariant c<=i<=f invariant sorted_seg(a,c,i) invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) invariant !b ==> sorted_seg(a,i,f) { var j:=f-1; b:=false; assert multiset(a[c..f]) == old(multiset(a[c..f])) ; while (j>i) decreases j-i//write invariant i<=j<=f-1//write invariant forall k::j<=k<=f-1 ==> a[j] <= a[k] invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant sorted_seg(a,c,i) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) invariant !b ==> sorted_seg(a,j,f) invariant multiset(a[c..f]) == old(multiset(a[c..f])) { if (a[j-1]>a[j]) { a[j],a[j-1]:=a[j-1],a[j]; b:=true; } j:=j-1; } assert !b ==> sorted_seg(a,i,f); i:=i+1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBubbleSort.dfy
1.4693
102
102
Dafny program: 102
predicate sorted_seg(a:array<int>, i:int, j:int) //j not included requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method selSort (a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) {if (c<=f-1){//two elements at least var i:=c; while (i<f-1) //outer loop { var less:=i; var j:=i+1; while (j<f) //inner loop { if (a[j]<a[less]) {less:=j;} j:=j+1; } a[i],a[less]:=a[less],a[i]; i:=i+1; } } }
predicate sorted_seg(a:array<int>, i:int, j:int) //j not included requires 0 <= i <= j <= a.Length reads a { forall l, k :: i <= l <= k < j ==> a[l] <= a[k] } method selSort (a:array<int>, c:int, f:int)//f excluded modifies a requires 0 <= c <= f <= a.Length //when c==f empty sequence ensures sorted_seg(a,c,f) ensures multiset(a[c..f]) == old(multiset(a[c..f])) ensures a[..c]==old(a[..c]) && a[f..]==old(a[f..]) {if (c<=f-1){//two elements at least var i:=c; while (i<f-1) //outer loop decreases f-i invariant c<=i<=f invariant sorted_seg(a,c,i) invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { var less:=i; var j:=i+1; while (j<f) //inner loop decreases f-j//write invariant i+1<=j<=f//write invariant i<=less<f invariant sorted_seg(a,c,i) invariant forall k::i<=k<j ==> a[less] <= a[k] invariant forall k,l::c<=k<i && i<=l<f ==> a[k]<=a[l] invariant multiset(a[c..f]) == old(multiset(a[c..f])) invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..]) { if (a[j]<a[less]) {less:=j;} j:=j+1; } a[i],a[less]:=a[less],a[i]; i:=i+1; } } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseSelSort.dfy
0.5619
103
103
Dafny program: 103
predicate strictNegative(v:array<int>,i:int,j:int) reads v requires 0<=i<=j<=v.Length {forall u | i<=u<j :: v[u]<0} predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} predicate isPermutation(s:seq<int>, t:seq<int>) {multiset(s)==multiset(t)} /** returns an index st new array is a permutation of the old array positive first and then strictnegative, i is the firs neg or len if not any */ method separate(v:array<int>) returns (i:int) modifies v ensures 0<=i<=v.Length ensures positive(v[0..i]) && strictNegative(v,i,v.Length) ensures isPermutation(v[0..v.Length], old(v[0..v.Length])) { i:=0; var j:=v.Length - 1; while(i<=j) { if(v[i]>=0){ i:=i+1; } else if(v[j]>=0){ v[i],v[j]:=v[j],v[i]; j:=j-1; i:=i+1; } else if(v[j]<0){ j:=j-1; } } }
predicate strictNegative(v:array<int>,i:int,j:int) reads v requires 0<=i<=j<=v.Length {forall u | i<=u<j :: v[u]<0} predicate positive(s:seq<int>) {forall u::0<=u<|s| ==> s[u]>=0} predicate isPermutation(s:seq<int>, t:seq<int>) {multiset(s)==multiset(t)} /** returns an index st new array is a permutation of the old array positive first and then strictnegative, i is the firs neg or len if not any */ method separate(v:array<int>) returns (i:int) modifies v ensures 0<=i<=v.Length ensures positive(v[0..i]) && strictNegative(v,i,v.Length) ensures isPermutation(v[0..v.Length], old(v[0..v.Length])) { i:=0; var j:=v.Length - 1; while(i<=j) decreases j-i invariant 0<=i<=j+1<=v.Length invariant strictNegative(v,j+1,v.Length) invariant positive(v[0..i]) invariant isPermutation(v[0..v.Length], old(v[0..v.Length])) { if(v[i]>=0){ i:=i+1; } else if(v[j]>=0){ assert v[i]<0; v[i],v[j]:=v[j],v[i]; j:=j-1; i:=i+1; } else if(v[j]<0){ j:=j-1; } } }
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseSeparate.dfy
0.4134
104
104
Dafny program: 104
predicate sorted_seg(a:array<int>, i:int, j:int) //i and j included requires 0 <= i <= j+1 <= a.Length reads a { forall l, k :: i <= l <= k <= j ==> a[l] <= a[k] } method InsertionSort(a: array<int>) modifies a; ensures sorted_seg(a,0,a.Length-1) ensures multiset(a[..]) == old(multiset(a[..])) //Add and prove this { var i := 0; while (i < a.Length) { var temp := a[i]; var j := i; while (j > 0 && temp < a[j - 1]) { a[j] := a[j - 1]; j := j - 1; } a[j] := temp; i := i + 1; } }
predicate sorted_seg(a:array<int>, i:int, j:int) //i and j included requires 0 <= i <= j+1 <= a.Length reads a { forall l, k :: i <= l <= k <= j ==> a[l] <= a[k] } method InsertionSort(a: array<int>) modifies a; ensures sorted_seg(a,0,a.Length-1) ensures multiset(a[..]) == old(multiset(a[..])) //Add and prove this { var i := 0; assert multiset(a[..]) == old(multiset(a[..])); while (i < a.Length) decreases a.Length-i invariant 0<=i<=a.Length invariant sorted_seg(a,0,i-1) invariant multiset(a[..]) == old(multiset(a[..]))//add invariant forall k::i<k<a.Length ==> a[k] == old(a[k]) { var temp := a[i]; var j := i; while (j > 0 && temp < a[j - 1]) decreases j invariant 0<=j<=i invariant sorted_seg(a,0,j-1) && sorted_seg(a,j+1,i) invariant forall k,l :: 0<=k<=j-1 && j+1<=l<=i ==> a[k]<=a[l] invariant forall k :: j<k<=i ==> temp <a[k] invariant forall k::i<k<a.Length ==> a[k] == old(a[k]) invariant multiset(a[..]) - multiset{a[j]} + multiset{temp} == old(multiset(a[..]))//add { a[j] := a[j - 1]; j := j - 1; } a[j] := temp; i := i + 1; } }
Dafny-Exercises_tmp_tmpjm75muf__Session8Exercises_ExerciseInsertionSort.dfy
0.5474
105
105
Dafny program: 105
function Sum(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length { if (i==j) then 0 else Sum(v,i,j-1)+v[j-1] } predicate SumMaxToRight(v:array<int>,i:int,s:int) reads v requires 0<=i<v.Length { forall l,ss {:induction l}::0<=l<=i && ss==i+1==> Sum(v,l,ss)<=s } method segMaxSum(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum(v,k,i+1) && SumMaxToRight(v,i,s) { s:=v[0]; k:=0; var j:=0; while (j<i) { if (s+v[j+1]>v[j+1]) {s:=s+v[j+1];} else {k:=j+1;s:=v[j+1];} j:=j+1; } } function Sum2(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length { if (i==j) then 0 else v[i]+Sum2(v,i+1,j) } //Now do the same but with a loop from right to left predicate SumMaxToRight2(v:array<int>,j:int,i:int,s:int)//maximum sum stuck to the right reads v requires 0<=j<=i<v.Length {(forall l,ss {:induction l}::j<=l<=i && ss==i+1 ==> Sum2(v,l,ss)<=s)} method segSumaMaxima2(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum2(v,k,i+1) && SumMaxToRight2(v,0,i,s) //Implement and verify { s:=v[i]; k:=i; var j:=i; var maxs:=s; while(j>0) { s:=s+v[j-1]; if(s>maxs){ maxs:=s; k:=j-1; } j:=j-1; } s:=maxs; }
function Sum(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length decreases j { if (i==j) then 0 else Sum(v,i,j-1)+v[j-1] } predicate SumMaxToRight(v:array<int>,i:int,s:int) reads v requires 0<=i<v.Length { forall l,ss {:induction l}::0<=l<=i && ss==i+1==> Sum(v,l,ss)<=s } method segMaxSum(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum(v,k,i+1) && SumMaxToRight(v,i,s) { s:=v[0]; k:=0; var j:=0; while (j<i) decreases i-j invariant 0<=j<=i invariant 0<=k<=j && s==Sum(v,k,j+1) invariant SumMaxToRight(v,j,s) { if (s+v[j+1]>v[j+1]) {s:=s+v[j+1];} else {k:=j+1;s:=v[j+1];} j:=j+1; } } function Sum2(v:array<int>,i:int,j:int):int reads v requires 0<=i<=j<=v.Length decreases j-i { if (i==j) then 0 else v[i]+Sum2(v,i+1,j) } //Now do the same but with a loop from right to left predicate SumMaxToRight2(v:array<int>,j:int,i:int,s:int)//maximum sum stuck to the right reads v requires 0<=j<=i<v.Length {(forall l,ss {:induction l}::j<=l<=i && ss==i+1 ==> Sum2(v,l,ss)<=s)} method segSumaMaxima2(v:array<int>,i:int) returns (s:int,k:int) requires v.Length>0 && 0<=i<v.Length ensures 0<=k<=i && s==Sum2(v,k,i+1) && SumMaxToRight2(v,0,i,s) //Implement and verify { s:=v[i]; k:=i; var j:=i; var maxs:=s; while(j>0) decreases j invariant 0<=j<=i invariant 0<=k<=i invariant s==Sum2(v,j,i+1) invariant SumMaxToRight2(v,j,i,maxs) invariant maxs==Sum2(v,k,i+1) { s:=s+v[j-1]; if(s>maxs){ maxs:=s; k:=j-1; } j:=j-1; } s:=maxs; }
Dafny-Exercises_tmp_tmpjm75muf__Session9Exercises_ExerciseSeqMaxSum.dfy
0.2215
107
107
Dafny program: 107
datatype Tree = Empty | Node(int,Tree,Tree) method Main() { var tree := BuildBST([-2,8,3,9,2,-7,0]); PrintTreeNumbersInorder(tree); } method PrintTreeNumbersInorder(t: Tree) { match t { case Empty => case Node(n, l, r) => PrintTreeNumbersInorder(l); print n; print "\n"; PrintTreeNumbersInorder(r); } } function NumbersInTree(t: Tree): set<int> { NumbersInSequence(Inorder(t)) } function NumbersInSequence(q: seq<int>): set<int> { set x | x in q } predicate BST(t: Tree) { Ascending(Inorder(t)) } function Inorder(t: Tree): seq<int> { match t { case Empty => [] case Node(n',nt1,nt2) => Inorder(nt1)+[n']+Inorder(nt2) } } predicate Ascending(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] < q[j] } predicate NoDuplicates(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] != q[j] } /* Goal: Implement correctly, clearly. No need to document the proof obligations. */ method BuildBST(q: seq<int>) returns (t: Tree) requires NoDuplicates(q) ensures BST(t) && NumbersInTree(t) == NumbersInSequence(q) { t := Empty; for i:=0 to |q| { t := InsertBST(t,q[i]); } } /* Goal: Implement correctly, efficiently, clearly, documenting the proof obligations as we've learned, with assertions and a lemma for each proof goal */ method InsertBST(t0: Tree, x: int) returns (t: Tree) requires BST(t0) && x !in NumbersInTree(t0) ensures BST(t) && NumbersInTree(t) == NumbersInTree(t0)+{x} { match t0 { case Empty => t := Node(x, Empty, Empty); case Node(i, left, right) => { var tmp:Tree:= Empty; if x < i { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(left, x); t := Node(i, tmp, right); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); // assert all_nums[..|left_nums|] == left_nums; ghost var new_all_nums := Inorder(t); ghost var new_left_nums := Inorder(tmp); // assert Ascending(new_left_nums+ [i] + right_nums); lemma_all_small(new_left_nums,i); } else { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(right, x); t := Node(i, left, tmp); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); // assert all_nums[..|left_nums|] == left_nums; ghost var new_all_nums := Inorder(t); ghost var new_right_nums := Inorder(tmp); // assert Ascending(left_nums+ [i] + right_nums); // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..]) ==> j > i; // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..])+{x} ==> j > i; lemma_all_big(new_right_nums,i); // assert Ascending(new_right_nums+[i]); } } } } lemma LemmaBinarySearchSubtree(n: int, left: Tree, right: Tree) requires BST(Node(n, left, right)) ensures BST(left) && BST(right) { var qleft, qright := Inorder(left), Inorder(right); var q := qleft+[n]+qright; } lemma LemmaAscendingSubsequence(q1: seq<int>, q2: seq<int>, i: nat) requires i <= |q1|-|q2| && q2 == q1[i..i+|q2|] requires Ascending(q1) ensures Ascending(q2) {} lemma {:verify true} lemma_all_small(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k < i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] < i {} lemma {:verify true} lemma_all_big(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k > i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] > i {}
datatype Tree = Empty | Node(int,Tree,Tree) method Main() { var tree := BuildBST([-2,8,3,9,2,-7,0]); PrintTreeNumbersInorder(tree); } method PrintTreeNumbersInorder(t: Tree) { match t { case Empty => case Node(n, l, r) => PrintTreeNumbersInorder(l); print n; print "\n"; PrintTreeNumbersInorder(r); } } function NumbersInTree(t: Tree): set<int> { NumbersInSequence(Inorder(t)) } function NumbersInSequence(q: seq<int>): set<int> { set x | x in q } predicate BST(t: Tree) { Ascending(Inorder(t)) } function Inorder(t: Tree): seq<int> { match t { case Empty => [] case Node(n',nt1,nt2) => Inorder(nt1)+[n']+Inorder(nt2) } } predicate Ascending(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] < q[j] } predicate NoDuplicates(q: seq<int>) { forall i,j :: 0 <= i < j < |q| ==> q[i] != q[j] } /* Goal: Implement correctly, clearly. No need to document the proof obligations. */ method BuildBST(q: seq<int>) returns (t: Tree) requires NoDuplicates(q) ensures BST(t) && NumbersInTree(t) == NumbersInSequence(q) { t := Empty; for i:=0 to |q| invariant BST(t); invariant NumbersInTree(t) == NumbersInSequence(q[..i]) { t := InsertBST(t,q[i]); } } /* Goal: Implement correctly, efficiently, clearly, documenting the proof obligations as we've learned, with assertions and a lemma for each proof goal */ method InsertBST(t0: Tree, x: int) returns (t: Tree) requires BST(t0) && x !in NumbersInTree(t0) ensures BST(t) && NumbersInTree(t) == NumbersInTree(t0)+{x} { match t0 { case Empty => t := Node(x, Empty, Empty); case Node(i, left, right) => { var tmp:Tree:= Empty; if x < i { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(left, x); t := Node(i, tmp, right); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); assert all_nums == left_nums + [i] + right_nums; assert all_nums[|left_nums|] == i; assert all_nums[|left_nums|+1..] == right_nums; // assert all_nums[..|left_nums|] == left_nums; assert Ascending(right_nums); assert Ascending(left_nums); assert Ascending(left_nums + [i] + right_nums); assert forall j,k :: |left_nums| < j < k < |all_nums| ==> x < i < all_nums[j] < all_nums[k]; ghost var new_all_nums := Inorder(t); ghost var new_left_nums := Inorder(tmp); assert new_all_nums == (new_left_nums + [i] + right_nums); assert Ascending([i]+right_nums); assert Ascending(new_left_nums); assert NumbersInSequence(new_left_nums) == NumbersInSequence(left_nums) + {x}; // assert Ascending(new_left_nums+ [i] + right_nums); assert forall j,k::0<= j < k <|all_nums| ==> all_nums[j]<all_nums[k]; assert forall j,k::0<= j < k <|left_nums| ==> all_nums[j]<all_nums[k]<all_nums[|left_nums|]; assert all_nums[|left_nums|] == i; assert left_nums == all_nums[..|left_nums|]; assert NumbersInSequence(new_left_nums) == NumbersInSequence(all_nums[..|left_nums|])+{x}; assert forall j,k::0<=j < k < |left_nums| ==> left_nums[j] < left_nums[k] < i; assert x < i; assert forall j :: j in NumbersInSequence(all_nums[..|left_nums|]) ==> j < i; assert forall j :: j in NumbersInSequence(all_nums[..|left_nums|])+{x} ==> j < i; assert forall j :: j in NumbersInSequence(new_left_nums) ==> j < i; assert forall j :: j in NumbersInSequence(new_left_nums) <==> j in new_left_nums; assert forall j,k::0<=j < k < |new_left_nums| ==> new_left_nums[j] < new_left_nums[k]; assert x < i; lemma_all_small(new_left_nums,i); assert forall j::0<=j < |new_left_nums| ==> new_left_nums[j] < i; assert Ascending(new_left_nums+[i]); assert Ascending(Inorder(t)); assert BST(t); } else { LemmaBinarySearchSubtree(i,left,right); tmp := InsertBST(right, x); t := Node(i, left, tmp); ghost var right_nums := Inorder(right); ghost var left_nums := Inorder(left); ghost var all_nums := Inorder(t0); assert all_nums == left_nums + [i] + right_nums; assert all_nums[|left_nums|] == i; assert all_nums[|left_nums|+1..] == right_nums; // assert all_nums[..|left_nums|] == left_nums; assert Ascending(right_nums); assert Ascending(left_nums); assert Ascending(left_nums + [i] + right_nums); assert forall j,k :: 0 <= j < k < |left_nums| ==> all_nums[j] < all_nums[k] < i < x; ghost var new_all_nums := Inorder(t); ghost var new_right_nums := Inorder(tmp); assert new_all_nums == (left_nums + [i] + new_right_nums); assert Ascending(left_nums + [i]); assert Ascending(new_right_nums); assert NumbersInSequence(new_right_nums) == NumbersInSequence(right_nums) + {x}; // assert Ascending(left_nums+ [i] + right_nums); assert forall j,k::0<= j < k <|all_nums| ==> all_nums[j]<all_nums[k]; assert forall j,k::|left_nums| < j < k < |all_nums|==> all_nums[|left_nums|]<all_nums[j]<all_nums[k]; assert all_nums[|left_nums|] == i; assert left_nums == all_nums[..|left_nums|]; assert NumbersInSequence(new_right_nums) == NumbersInSequence(all_nums[|left_nums|+1..])+{x}; assert forall j,k::0<=j < k < |right_nums| ==> i < right_nums[j] < right_nums[k] ; assert x > i; // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..]) ==> j > i; // assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..])+{x} ==> j > i; assert forall j :: j in NumbersInSequence(new_right_nums) ==> j > i; assert forall j :: j in NumbersInSequence(new_right_nums) <==> j in new_right_nums; assert forall j,k::0<=j < k < |new_right_nums| ==> new_right_nums[j] < new_right_nums[k]; assert x > i; lemma_all_big(new_right_nums,i); assert forall j::0<=j < |new_right_nums| ==> new_right_nums[j] > i; // assert Ascending(new_right_nums+[i]); assert Ascending(Inorder(t)); assert BST(t); } } } } lemma LemmaBinarySearchSubtree(n: int, left: Tree, right: Tree) requires BST(Node(n, left, right)) ensures BST(left) && BST(right) { assert Ascending(Inorder(Node(n, left, right))); var qleft, qright := Inorder(left), Inorder(right); var q := qleft+[n]+qright; assert q == Inorder(Node(n, left, right)); assert Ascending(qleft+[n]+qright); assert Ascending(qleft) by { LemmaAscendingSubsequence(q, qleft, 0); } assert Ascending(qright) by { LemmaAscendingSubsequence(q, qright, |qleft|+1); } } lemma LemmaAscendingSubsequence(q1: seq<int>, q2: seq<int>, i: nat) requires i <= |q1|-|q2| && q2 == q1[i..i+|q2|] requires Ascending(q1) ensures Ascending(q2) {} lemma {:verify true} lemma_all_small(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k < i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] < i {} lemma {:verify true} lemma_all_big(q:seq<int>,i:int) requires forall k:: k in NumbersInSequence(q) ==> k > i requires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q) ensures forall j::0<=j < |q| ==> q[j] > i {}
Dafny-Practice_tmp_tmphnmt4ovh_BST.dfy
2.7606
109
109
Dafny program: 109
method ArraySplit (a : array<int>) returns (b : array<int>, c : array<int>) ensures fresh(b) ensures fresh(c) ensures a[..] == b[..] + c[..] ensures a.Length == b.Length + c.Length ensures a.Length > 1 ==> a.Length > b.Length ensures a.Length > 1 ==> a.Length > c.Length { var splitPoint : int := a.Length / 2; b := new int[splitPoint]; c := new int[a.Length - splitPoint]; var i : int := 0; while (i < splitPoint) { b[i] := a[i]; i := i + 1; } // while(i < a.Length) // invariant splitPoint <= i <= a.Length // invariant c[..i-splitPoint] == a[..i] // { // c[i] := a[i]; // i := i+1; // } var j : int := 0; while (i < a.Length) { c[j] := a[i]; i := i + 1; j := j + 1; } }
method ArraySplit (a : array<int>) returns (b : array<int>, c : array<int>) ensures fresh(b) ensures fresh(c) ensures a[..] == b[..] + c[..] ensures a.Length == b.Length + c.Length ensures a.Length > 1 ==> a.Length > b.Length ensures a.Length > 1 ==> a.Length > c.Length { var splitPoint : int := a.Length / 2; b := new int[splitPoint]; c := new int[a.Length - splitPoint]; var i : int := 0; while (i < splitPoint) invariant 0 <= i <= splitPoint invariant b[..i] == a[..i] { b[i] := a[i]; i := i + 1; } // while(i < a.Length) // invariant splitPoint <= i <= a.Length // invariant c[..i-splitPoint] == a[..i] // { // c[i] := a[i]; // i := i+1; // } var j : int := 0; while (i < a.Length) invariant splitPoint <= i <= a.Length invariant j == i - splitPoint invariant c[..j] == a[splitPoint..i] invariant b[..] + c[..j] == a[..i] { c[j] := a[i]; i := i + 1; j := j + 1; } }
Dafny-Projects_tmp_tmph399drhy_p2_arraySplit.dfy
0.2046
111
111
Dafny program: 111
/******************************************************************************* * Copyright by the contributors to the Dafny Project * SPDX-License-Identifier: MIT *******************************************************************************/ module Helper { /************ Definitions ************/ function Power(b: nat, n: nat): (p: nat) ensures b > 0 ==> p > 0 { match n case 0 => 1 case 1 => b case _ => b * Power(b, n - 1) } function Log2Floor(n: nat): nat requires n >= 1 { if n < 2 then 0 else Log2Floor(n / 2) + 1 } lemma Log2FloorDef(n: nat) requires n >= 1 ensures Log2Floor(2 * n) == Log2Floor(n) + 1 {} function boolToNat(b: bool): nat { if b then 1 else 0 } /******* Lemmas *******/ lemma Congruence<T, U>(x: T, y: T, f: T -> U) requires x == y ensures f(x) == f(y) {} lemma DivisionSubstituteAlternativeReal(x: real, a: real, b: real) requires a == b requires x != 0.0 ensures a / x == b / x {} lemma DivModAddDenominator(n: nat, m: nat) requires m > 0 ensures (n + m) / m == n / m + 1 ensures (n + m) % m == n % m { var zp := (n + m) / m - n / m - 1; } lemma DivModIsUnique(n: int, m: int, a: int, b: int) requires n >= 0 requires m > 0 requires 0 <= b < m requires n == a * m + b ensures a == n / m ensures b == n % m { if a == 0 { } else { } } lemma DivModAddMultiple(a: nat, b: nat, c: nat) requires a > 0 ensures (c * a + b) / a == c + b / a ensures (c * a + b) % a == b % a { calc { a * c + b; == a * c + (a * (b / a) + b % a); == a * (c + b / a) + b % a; } DivModIsUnique(a * c + b, a, c + b / a, b % a); } lemma DivisionByTwo(x: real) ensures 0.5 * x == x / 2.0 {} lemma PowerGreater0(base: nat, exponent: nat) requires base >= 1 ensures Power(base, exponent) >= 1 {} lemma Power2OfLog2Floor(n: nat) requires n >= 1 ensures Power(2, Log2Floor(n)) <= n < Power(2, Log2Floor(n) + 1) {} lemma NLtPower2Log2FloorOf2N(n: nat) requires n >= 1 ensures n < Power(2, Log2Floor(2 * n)) { calc { n; < { Power2OfLog2Floor(n); } Power(2, Log2Floor(n) + 1); == { Log2FloorDef(n); } Power(2, Log2Floor(2 * n)); } } lemma MulMonotonic(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d ensures a * b <= c * d { calc { a * b; <= c * b; <= c * d; } } lemma MulMonotonicStrictRhs(b: nat, c: nat, d: nat) requires b < d requires c > 0 ensures c * b < c * d {} lemma MulMonotonicStrict(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d requires (a != c && d > 0) || (b != d && c > 0) ensures a * b < c * d { if a != c && d > 0 { calc { a * b; <= { MulMonotonic(a, b, a, d); } a * d; < c * d; } } if b != d && c > 0 { calc { a * b; <= c * b; < { MulMonotonicStrictRhs(b, c, d); } c * d; } } } lemma AdditionOfFractions(x: real, y: real, z: real) requires z != 0.0 ensures (x / z) + (y / z) == (x + y) / z {} lemma DivSubstituteDividend(x: real, y: real, z: real) requires y != 0.0 requires x == z ensures x / y == z / y {} lemma DivSubstituteDivisor(x: real, y: real, z: real) requires y != 0.0 requires y == z ensures x / y == x / z {} lemma DivDivToDivMul(x: real, y: real, z: real) requires y != 0.0 requires z != 0.0 ensures (x / y) / z == x / (y * z) {} lemma NatMulNatToReal(x: nat, y: nat) ensures (x * y) as real == (x as real) * (y as real) {} lemma SimplifyFractions(x: real, y: real, z: real) requires z != 0.0 requires y != 0.0 ensures (x / z) / (y / z) == x / y {} lemma PowerOfTwoLemma(k: nat) ensures (1.0 / Power(2, k) as real) / 2.0 == 1.0 / (Power(2, k + 1) as real) { calc { (1.0 / Power(2, k) as real) / 2.0; == { DivDivToDivMul(1.0, Power(2, k) as real, 2.0); } 1.0 / (Power(2, k) as real * 2.0); == { NatMulNatToReal(Power(2, k), 2); } 1.0 / (Power(2, k) * 2) as real; == 1.0 / (Power(2, k + 1) as real); } } }
/******************************************************************************* * Copyright by the contributors to the Dafny Project * SPDX-License-Identifier: MIT *******************************************************************************/ module Helper { /************ Definitions ************/ function Power(b: nat, n: nat): (p: nat) ensures b > 0 ==> p > 0 { match n case 0 => 1 case 1 => b case _ => b * Power(b, n - 1) } function Log2Floor(n: nat): nat requires n >= 1 decreases n { if n < 2 then 0 else Log2Floor(n / 2) + 1 } lemma Log2FloorDef(n: nat) requires n >= 1 ensures Log2Floor(2 * n) == Log2Floor(n) + 1 {} function boolToNat(b: bool): nat { if b then 1 else 0 } /******* Lemmas *******/ lemma Congruence<T, U>(x: T, y: T, f: T -> U) requires x == y ensures f(x) == f(y) {} lemma DivisionSubstituteAlternativeReal(x: real, a: real, b: real) requires a == b requires x != 0.0 ensures a / x == b / x {} lemma DivModAddDenominator(n: nat, m: nat) requires m > 0 ensures (n + m) / m == n / m + 1 ensures (n + m) % m == n % m { var zp := (n + m) / m - n / m - 1; assert 0 == m * zp + ((n + m) % m) - (n % m); } lemma DivModIsUnique(n: int, m: int, a: int, b: int) requires n >= 0 requires m > 0 requires 0 <= b < m requires n == a * m + b ensures a == n / m ensures b == n % m { if a == 0 { assert n == b; } else { assert (n - m) / m == a - 1 && (n - m) % m == b by { DivModIsUnique(n - m, m, a - 1, b); } assert n / m == a && n % m == b by { DivModAddDenominator(n - m, m); } } } lemma DivModAddMultiple(a: nat, b: nat, c: nat) requires a > 0 ensures (c * a + b) / a == c + b / a ensures (c * a + b) % a == b % a { calc { a * c + b; == a * c + (a * (b / a) + b % a); == a * (c + b / a) + b % a; } DivModIsUnique(a * c + b, a, c + b / a, b % a); } lemma DivisionByTwo(x: real) ensures 0.5 * x == x / 2.0 {} lemma PowerGreater0(base: nat, exponent: nat) requires base >= 1 ensures Power(base, exponent) >= 1 {} lemma Power2OfLog2Floor(n: nat) requires n >= 1 ensures Power(2, Log2Floor(n)) <= n < Power(2, Log2Floor(n) + 1) {} lemma NLtPower2Log2FloorOf2N(n: nat) requires n >= 1 ensures n < Power(2, Log2Floor(2 * n)) { calc { n; < { Power2OfLog2Floor(n); } Power(2, Log2Floor(n) + 1); == { Log2FloorDef(n); } Power(2, Log2Floor(2 * n)); } } lemma MulMonotonic(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d ensures a * b <= c * d { calc { a * b; <= c * b; <= c * d; } } lemma MulMonotonicStrictRhs(b: nat, c: nat, d: nat) requires b < d requires c > 0 ensures c * b < c * d {} lemma MulMonotonicStrict(a: nat, b: nat, c: nat, d: nat) requires a <= c requires b <= d requires (a != c && d > 0) || (b != d && c > 0) ensures a * b < c * d { if a != c && d > 0 { calc { a * b; <= { MulMonotonic(a, b, a, d); } a * d; < c * d; } } if b != d && c > 0 { calc { a * b; <= c * b; < { MulMonotonicStrictRhs(b, c, d); } c * d; } } } lemma AdditionOfFractions(x: real, y: real, z: real) requires z != 0.0 ensures (x / z) + (y / z) == (x + y) / z {} lemma DivSubstituteDividend(x: real, y: real, z: real) requires y != 0.0 requires x == z ensures x / y == z / y {} lemma DivSubstituteDivisor(x: real, y: real, z: real) requires y != 0.0 requires y == z ensures x / y == x / z {} lemma DivDivToDivMul(x: real, y: real, z: real) requires y != 0.0 requires z != 0.0 ensures (x / y) / z == x / (y * z) {} lemma NatMulNatToReal(x: nat, y: nat) ensures (x * y) as real == (x as real) * (y as real) {} lemma SimplifyFractions(x: real, y: real, z: real) requires z != 0.0 requires y != 0.0 ensures (x / z) / (y / z) == x / y {} lemma PowerOfTwoLemma(k: nat) ensures (1.0 / Power(2, k) as real) / 2.0 == 1.0 / (Power(2, k + 1) as real) { calc { (1.0 / Power(2, k) as real) / 2.0; == { DivDivToDivMul(1.0, Power(2, k) as real, 2.0); } 1.0 / (Power(2, k) as real * 2.0); == { NatMulNatToReal(Power(2, k), 2); } 1.0 / (Power(2, k) * 2) as real; == 1.0 / (Power(2, k + 1) as real); } } }
Dafny-VMC_tmp_tmpzgqv0i1u_src_Math_Helper.dfy
1.2308
114
114
Dafny program: 114
/* Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. */ predicate sorted_between(A:array<int>, from:int, to:int) reads A { forall i, j :: 0 <= i <= j < A.Length && from <= i <= j <= to ==> A[i] <= A[j] } predicate sorted(A:array<int>) reads A { sorted_between(A, 0, A.Length-1) } method BubbleSort(A:array<int>) modifies A ensures sorted(A) ensures multiset(A[..]) == multiset(old(A[..])) { var N := A.Length; var i := N-1; while 0 < i { print A[..], "\n"; var j := 0; while j < i { if A[j] > A[j+1] { A[j], A[j+1] := A[j+1], A[j]; print A[..], "\n"; } j := j+1; } i := i-1; print "\n"; } } method Main() { var A := new int[10]; A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[8], A[9] := 2, 4, 6, 15, 3, 19, 17, 16, 18, 1; BubbleSort(A); print A[..]; } /* Explanation: // A is ordered for each pair of elements such that // the first element belongs to the left partition of i // and the second element belongs to the right partition of i // There is a variable defined by the value that the array takes at position j // Therefore, each value that the array takes for all elements from 0 to j // They are less than or equal to the value of the variable */
/* Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. */ predicate sorted_between(A:array<int>, from:int, to:int) reads A { forall i, j :: 0 <= i <= j < A.Length && from <= i <= j <= to ==> A[i] <= A[j] } predicate sorted(A:array<int>) reads A { sorted_between(A, 0, A.Length-1) } method BubbleSort(A:array<int>) modifies A ensures sorted(A) ensures multiset(A[..]) == multiset(old(A[..])) { var N := A.Length; var i := N-1; while 0 < i invariant multiset(A[..]) == multiset(old(A[..])) invariant sorted_between(A, i, N-1) invariant forall n, m :: 0 <= n <= i < m < N ==> A[n] <= A[m] decreases i { print A[..], "\n"; var j := 0; while j < i invariant 0 < i < N invariant 0 <= j <= i invariant multiset(A[..]) == multiset(old(A[..])) invariant sorted_between(A, i, N-1) invariant forall n, m :: 0 <= n <= i < m < N ==> A[n] <= A[m] invariant forall n :: 0 <= n <= j ==> A[n] <= A[j] decreases i - j { if A[j] > A[j+1] { A[j], A[j+1] := A[j+1], A[j]; print A[..], "\n"; } j := j+1; } i := i-1; print "\n"; } } method Main() { var A := new int[10]; A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[8], A[9] := 2, 4, 6, 15, 3, 19, 17, 16, 18, 1; BubbleSort(A); print A[..]; } /* Explanation: invariant forall n, m :: 0 <= n <= i <m <N ==> A [n] <= A [m] // A is ordered for each pair of elements such that // the first element belongs to the left partition of i // and the second element belongs to the right partition of i invariant forall n :: 0 <= n <= j ==> A [n] <= A [j] // There is a variable defined by the value that the array takes at position j // Therefore, each value that the array takes for all elements from 0 to j // They are less than or equal to the value of the variable */
Dafny-programs_tmp_tmpnso9eu7u_Algorithms + sorting_bubble-sort.dfy
1.745
119
119
Dafny program: 119
/** This ADT represents a multiset. */ trait MyMultiset { // internal invariant ghost predicate Valid() reads this // abstract variable ghost var theMultiset: multiset<int> method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() ensures theMultiset == old(theMultiset) + multiset{elem} ensures didChange ghost predicate Contains(elem: int) reads this { elem in theMultiset } method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange method Length() returns (len: int) requires Valid() ensures Valid() ensures len == |theMultiset| method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset } /** This implementation implements the ADT with a map. */ class MultisetImplementationWithMap extends MyMultiset { // valid invariant predicate of the ADT implementation ghost predicate Valid() reads this { (forall i | i in elements.Keys :: elements[i] > 0) && (theMultiset == A(elements)) && (forall i :: i in elements.Keys <==> Contains(i)) } // the abstraction function function A(m: map<int, nat>): (s:multiset<int>) ensures (forall i | i in m :: m[i] == A(m)[i]) && (m == map[] <==> A(m) == multiset{}) && (forall i :: i in m <==> i in A(m)) // lemma for the opposite of the abstraction function lemma LemmaReverseA(m: map<int, nat>, s : seq<int>) requires (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) ensures A(m) == multiset(s) // ADT concrete implementation variable var elements: map<int, nat>; // constructor of the implementation class that ensures the implementation invariant constructor MultisetImplementationWithMap() ensures Valid() ensures elements == map[] ensures theMultiset == multiset{} { elements := map[]; theMultiset := multiset{}; } //adds an element to the multiset method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures elem in elements ==> elements == elements[elem := elements[elem]] ensures theMultiset == old(theMultiset) + multiset{elem} ensures !(elem in elements) ==> elements == elements[elem := 1] ensures didChange ensures Contains(elem) ensures Valid() { if !(elem in elements) { elements := elements[elem := 1]; } else { elements := elements[elem := (elements[elem] + 1)]; } didChange := true; theMultiset := A(elements); } //removes an element from the multiset method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange ensures didChange <==> elements != old(elements) { /* If the multiset does not contain the element */ if elem !in elements { return false; } /* If the multiset contains the element */ elements := elements[elem := elements[elem] - 1]; if(elements[elem] == 0) { elements := elements - {elem}; } theMultiset := A(elements); didChange := true; } //gets the length of the multiset method Length() returns (len: int) requires Valid() ensures len == |theMultiset| { var result := Map2Seq(elements); return |result|; } //compares the current multiset with another multiset and determines if they're equal method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset { var otherMapSeq := other.getElems(); var c := this.getElems(); return multiset(c) == multiset(otherMapSeq); } //gets the elements of the multiset as a sequence method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset { var result : seq<int>; result := Map2Seq(elements); return result; } //Transforms a map to a sequence method Map2Seq(m: map<int, nat>) returns (s: seq<int>) requires forall i | i in m.Keys :: i in m.Keys <==> m[i] > 0 ensures forall i | i in m.Keys :: multiset(s)[i] == m[i] ensures forall i | i in m.Keys :: i in s ensures A(m) == multiset(s) ensures (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) { if |m| == 0 {return []; } var keys := m.Keys; var key: int; s := []; while keys != {} { key :| key in keys; var counter := 0; while counter < m[key] { s := s + [key]; counter := counter + 1; } keys := keys - {key}; } LemmaReverseA(m, s); } method Test1() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); //declaring the other bag var theOtherBag : MultisetImplementationWithMap; theOtherBag := new MultisetImplementationWithMap.MultisetImplementationWithMap(); // equals test - unequal bags var b:= this.equals(theOtherBag); // equals test - equal bags theOtherBag.theMultiset := multiset{1, 2, 3, 4}; theOtherBag.elements := map[1 := 1, 2:=1, 3:=1,4:=1]; var c:= this.equals(theOtherBag); } method Test2() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); //add test var d := this.Add(3); var e := this.getElems(); //remove test var f := this.Remove(4); var g := this.getElems(); //length test var h := this.Length(); } method Test3() { //test Map2Seq var m := map[2:= 2, 3:=3, 4:= 4]; var s :seq<int> := [2, 2, 3, 3, 3, 4, 4,4 ,4]; var a := this.Map2Seq(m); var x := map[1 := 1, 2:= 1, 3:= 1]; var y :seq<int> := [1, 2, 3]; var z := this.Map2Seq(x); } }
/** This ADT represents a multiset. */ trait MyMultiset { // internal invariant ghost predicate Valid() reads this // abstract variable ghost var theMultiset: multiset<int> method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() ensures theMultiset == old(theMultiset) + multiset{elem} ensures didChange ghost predicate Contains(elem: int) reads this { elem in theMultiset } method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange method Length() returns (len: int) requires Valid() ensures Valid() ensures len == |theMultiset| method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset } /** This implementation implements the ADT with a map. */ class MultisetImplementationWithMap extends MyMultiset { // valid invariant predicate of the ADT implementation ghost predicate Valid() reads this { (forall i | i in elements.Keys :: elements[i] > 0) && (theMultiset == A(elements)) && (forall i :: i in elements.Keys <==> Contains(i)) } // the abstraction function function A(m: map<int, nat>): (s:multiset<int>) ensures (forall i | i in m :: m[i] == A(m)[i]) && (m == map[] <==> A(m) == multiset{}) && (forall i :: i in m <==> i in A(m)) // lemma for the opposite of the abstraction function lemma LemmaReverseA(m: map<int, nat>, s : seq<int>) requires (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) ensures A(m) == multiset(s) // ADT concrete implementation variable var elements: map<int, nat>; // constructor of the implementation class that ensures the implementation invariant constructor MultisetImplementationWithMap() ensures Valid() ensures elements == map[] ensures theMultiset == multiset{} { elements := map[]; theMultiset := multiset{}; } //adds an element to the multiset method Add(elem: int) returns (didChange: bool) modifies this requires Valid() ensures elem in elements ==> elements == elements[elem := elements[elem]] ensures theMultiset == old(theMultiset) + multiset{elem} ensures !(elem in elements) ==> elements == elements[elem := 1] ensures didChange ensures Contains(elem) ensures Valid() { if !(elem in elements) { elements := elements[elem := 1]; } else { elements := elements[elem := (elements[elem] + 1)]; } didChange := true; theMultiset := A(elements); } //removes an element from the multiset method Remove(elem: int) returns (didChange: bool) modifies this requires Valid() ensures Valid() /* If the multiset contains the element */ ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem} ensures old(Contains(elem)) ==> didChange /* If the multiset does not contain the element */ ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset) ensures ! old(Contains(elem)) ==> ! didChange ensures didChange <==> elements != old(elements) { /* If the multiset does not contain the element */ if elem !in elements { assert ! Contains(elem); assert theMultiset == old(theMultiset); assert Valid(); return false; } /* If the multiset contains the element */ assert Contains(elem); elements := elements[elem := elements[elem] - 1]; if(elements[elem] == 0) { elements := elements - {elem}; } theMultiset := A(elements); didChange := true; } //gets the length of the multiset method Length() returns (len: int) requires Valid() ensures len == |theMultiset| { var result := Map2Seq(elements); return |result|; } //compares the current multiset with another multiset and determines if they're equal method equals(other: MyMultiset) returns (equal?: bool) requires Valid() requires other.Valid() ensures Valid() ensures equal? <==> theMultiset == other.theMultiset { var otherMapSeq := other.getElems(); assert multiset(otherMapSeq) == other.theMultiset; var c := this.getElems(); return multiset(c) == multiset(otherMapSeq); } //gets the elements of the multiset as a sequence method getElems() returns (elems: seq<int>) requires Valid() ensures Valid() ensures multiset(elems) == theMultiset { var result : seq<int>; result := Map2Seq(elements); return result; } //Transforms a map to a sequence method Map2Seq(m: map<int, nat>) returns (s: seq<int>) requires forall i | i in m.Keys :: i in m.Keys <==> m[i] > 0 ensures forall i | i in m.Keys :: multiset(s)[i] == m[i] ensures forall i | i in m.Keys :: i in s ensures A(m) == multiset(s) ensures (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{}) { if |m| == 0 {return []; } var keys := m.Keys; var key: int; s := []; while keys != {} invariant forall i | i in m.Keys :: i in keys <==> multiset(s)[i] == 0 invariant forall i | i in m.Keys - keys :: multiset(s)[i] == m[i] { key :| key in keys; var counter := 0; while counter < m[key] invariant 0 <= counter <= m[key] invariant multiset(s)[key] == counter invariant forall i | i in m.Keys && i != key :: i in keys <==> multiset(s)[i] == 0 invariant forall i | i in m.Keys - keys :: multiset(s)[i] == m[i]; { s := s + [key]; counter := counter + 1; } keys := keys - {key}; } LemmaReverseA(m, s); } method Test1() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); assert multiset(a) == multiset{1, 2, 3, 4}; //declaring the other bag var theOtherBag : MultisetImplementationWithMap; theOtherBag := new MultisetImplementationWithMap.MultisetImplementationWithMap(); // equals test - unequal bags var b:= this.equals(theOtherBag); assert b == false; // equals test - equal bags theOtherBag.theMultiset := multiset{1, 2, 3, 4}; theOtherBag.elements := map[1 := 1, 2:=1, 3:=1,4:=1]; var c:= this.equals(theOtherBag); assert c == true; } method Test2() modifies this { assume this.theMultiset == multiset{1, 2, 3, 4}; assume this.Valid(); // get elements test var a := this.getElems(); assert multiset(a) == multiset{1, 2, 3, 4}; //add test var d := this.Add(3); var e := this.getElems(); assert multiset(e) == multiset([1, 2, 3, 4, 3]); //remove test var f := this.Remove(4); var g := this.getElems(); assert multiset(g) == multiset([1, 2, 3, 3]); //length test var h := this.Length(); assert h == 4; } method Test3() { //test Map2Seq var m := map[2:= 2, 3:=3, 4:= 4]; var s :seq<int> := [2, 2, 3, 3, 3, 4, 4,4 ,4]; var a := this.Map2Seq(m); assert multiset(a) == multiset(s); var x := map[1 := 1, 2:= 1, 3:= 1]; var y :seq<int> := [1, 2, 3]; var z := this.Map2Seq(x); assert multiset(z) == multiset(y); } }
DafnyPrograms_tmp_tmp74_f9k_c_map-multiset-implementation.dfy
1.608
120
120
Dafny program: 120
//predicate for primeness ghost predicate prime(n: nat) { n > 1 && (forall nr | 1 < nr < n :: n % nr != 0) } datatype Answer = Yes | No | Unknown //the class containing a prime database, if a number is prime it returns Yes, if it is not No and if the number //is not in the database it returns Unknown class {:autocontracts} PrimeMap{ var database: map<nat, bool>; //the valid invariant of the class ghost predicate Valid() reads this { forall i | i in database.Keys :: (database[i] == true <==> prime(i)) } //the constructor constructor() ensures database == map[] { database := map[]; } // insert an already known prime number into the database method InsertPrime(n: nat) modifies this; ensures database.Keys == old(database.Keys) + {n} requires prime(n) ensures database == database[n := true] { database := database[n := true]; } // check the primeness of n and insert it accordingly into the database method InsertNumber(n: nat) modifies this ensures database.Keys == old(database.Keys) + {n} ensures prime(n) <==> database == database[n := true] ensures !prime(n) <==> database == database[n := false] { var prime : bool; prime := testPrimeness(n); database := database[n := prime]; } // lookup n in the database and reply with Yes or No if it's in the database and it is or it is not prime, // or with Unknown when it's not in the databse method IsPrime?(n: nat) returns (answer: Answer) ensures database.Keys == old(database.Keys) ensures (n in database) && prime(n) <==> answer == Yes ensures (n in database) && !prime(n) <==> answer == No ensures !(n in database) <==> answer == Unknown { if !(n in database){ return Unknown; } else if database[n] == true { return Yes; } else if database[n] == false { return No; } } // method to test whether a number is prime, returns bool method testPrimeness(n: nat) returns (result: bool) requires n >= 0 ensures result <==> prime(n) { if n == 0 || n == 1{ return false; } var i := 2; result := true; while i < n { if n % i == 0 { result := false; } i := i + 1; } } } method testingMethod() { // witness to prove to dafny (exists nr | 1 < nr < n :: n % nr != 0), since // the !(forall nr | 1 < nr < n :: n % nr != 0) from !prime predicate ==> (exists nr | 1 < nr < n :: n % nr == 0) var pm := new PrimeMap(); // InsertPrime test pm.InsertPrime(13); // InsertNumber test pm.InsertNumber(17); pm.InsertNumber(15); var result: Answer := pm.IsPrime?(17); var result2: Answer := pm.IsPrime?(15); var result3: Answer := pm.IsPrime?(454); var result4: Answer := pm.IsPrime?(13); }
//predicate for primeness ghost predicate prime(n: nat) { n > 1 && (forall nr | 1 < nr < n :: n % nr != 0) } datatype Answer = Yes | No | Unknown //the class containing a prime database, if a number is prime it returns Yes, if it is not No and if the number //is not in the database it returns Unknown class {:autocontracts} PrimeMap{ var database: map<nat, bool>; //the valid invariant of the class ghost predicate Valid() reads this { forall i | i in database.Keys :: (database[i] == true <==> prime(i)) } //the constructor constructor() ensures database == map[] { database := map[]; } // insert an already known prime number into the database method InsertPrime(n: nat) modifies this; ensures database.Keys == old(database.Keys) + {n} requires prime(n) ensures database == database[n := true] { database := database[n := true]; } // check the primeness of n and insert it accordingly into the database method InsertNumber(n: nat) modifies this ensures database.Keys == old(database.Keys) + {n} ensures prime(n) <==> database == database[n := true] ensures !prime(n) <==> database == database[n := false] { var prime : bool; prime := testPrimeness(n); database := database[n := prime]; } // lookup n in the database and reply with Yes or No if it's in the database and it is or it is not prime, // or with Unknown when it's not in the databse method IsPrime?(n: nat) returns (answer: Answer) ensures database.Keys == old(database.Keys) ensures (n in database) && prime(n) <==> answer == Yes ensures (n in database) && !prime(n) <==> answer == No ensures !(n in database) <==> answer == Unknown { if !(n in database){ return Unknown; } else if database[n] == true { return Yes; } else if database[n] == false { return No; } } // method to test whether a number is prime, returns bool method testPrimeness(n: nat) returns (result: bool) requires n >= 0 ensures result <==> prime(n) { if n == 0 || n == 1{ return false; } var i := 2; result := true; while i < n invariant i >= 2 && i <= n invariant result <==> (forall j | 1 < j <= i - 1 :: n % j != 0) { if n % i == 0 { result := false; } i := i + 1; } } } method testingMethod() { // witness to prove to dafny (exists nr | 1 < nr < n :: n % nr != 0), since // the !(forall nr | 1 < nr < n :: n % nr != 0) from !prime predicate ==> (exists nr | 1 < nr < n :: n % nr == 0) assert !(forall nr | 1 < nr < 15 :: 15 % nr != 0) ==> (exists nr | 1 < nr < 15 :: 15 % nr == 0); assert 15 % 3 == 0; assert(exists nr | 1 < nr < 15 :: 15 % nr == 0); var pm := new PrimeMap(); // InsertPrime test pm.InsertPrime(13); // InsertNumber test pm.InsertNumber(17); pm.InsertNumber(15); assert pm.database.Keys == {17, 15, 13}; var result: Answer := pm.IsPrime?(17); assert result == Yes; var result2: Answer := pm.IsPrime?(15); assert result2 == No; var result3: Answer := pm.IsPrime?(454); assert result3 == Unknown; var result4: Answer := pm.IsPrime?(13); assert result4 == Yes; }
DafnyPrograms_tmp_tmp74_f9k_c_prime-database.dfy
2.6634
121
121
Dafny program: 121
/* * Formal specification and verification of a dynamic programming algorithm for calculating C(n, k). * FEUP, MIEIC, MFES, 2020/21. */ // Initial recursive definition of C(n, k), based on the Pascal equality. function comb(n: nat, k: nat): nat requires 0 <= k <= n { if k == 0 || k == n then 1 else comb(n-1, k) + comb(n-1, k-1) } by method // Calculates C(n,k) iteratively in time O(k*(n-k)) and space O(n-k), // with dynamic programming. { var maxj := n - k; var c := new nat[1 + maxj]; forall i | 0 <= i <= maxj { c[i] := 1; } var i := 1; while i <= k { var j := 1; while j <= maxj { c[j] := c[j] + c[j-1]; j := j+1; } i := i + 1; } return c[maxj]; } lemma combProps(n: nat, k: nat) requires 0 <= k <= n ensures comb(n, k) == comb(n, n-k) {} method Main() { // Statically checked (proved) test cases! var res1 := comb(40, 10); print "combDyn(40, 10) = ", res1, "\n"; } method testComb() { }
/* * Formal specification and verification of a dynamic programming algorithm for calculating C(n, k). * FEUP, MIEIC, MFES, 2020/21. */ // Initial recursive definition of C(n, k), based on the Pascal equality. function comb(n: nat, k: nat): nat requires 0 <= k <= n { if k == 0 || k == n then 1 else comb(n-1, k) + comb(n-1, k-1) } by method // Calculates C(n,k) iteratively in time O(k*(n-k)) and space O(n-k), // with dynamic programming. { var maxj := n - k; var c := new nat[1 + maxj]; forall i | 0 <= i <= maxj { c[i] := 1; } var i := 1; while i <= k invariant 1 <= i <= k + 1 invariant forall j :: 0 <= j <= maxj ==> c[j] == comb(j + i - 1, i - 1) { var j := 1; while j <= maxj invariant 1 <= j <= maxj + 1 invariant forall j' :: 0 <= j' < j ==> c[j'] == comb(j' + i, i) invariant forall j' :: j <= j' <= maxj ==> c[j'] == comb(j' + i - 1, i - 1) { c[j] := c[j] + c[j-1]; j := j+1; } i := i + 1; } return c[maxj]; } lemma combProps(n: nat, k: nat) requires 0 <= k <= n ensures comb(n, k) == comb(n, n-k) {} method Main() { // Statically checked (proved) test cases! assert comb(5, 2) == 10; assert comb(5, 0) == 1; assert comb(5, 5) == 1; assert comb(5, 2) == 10; var res1 := comb(40, 10); print "combDyn(40, 10) = ", res1, "\n"; } method testComb() { assert comb(6, 2) == 15; assert comb(6, 3) == 20; assert comb(6, 4) == 15; assert comb(6, 6) == 1; }
DafnyProjects_tmp_tmp2acw_s4s_CombNK.dfy
0.7165
123
123
Dafny program: 123
/* * Formal verification of an O(log n) algorithm to calculate the natural power of a real number (x^n), * illustrating the usage of lemmas and automatic induction in Dafny. * J. Pascoal Faria, FEUP, Jan/2022. */ // Recursive definition of x^n in functional style, with time and space complexity O(n). function power(x: real, n: nat) : real { if n == 0 then 1.0 else x * power(x, n-1) } // Computation of x^n in time and space O(log n). method powerDC(x: real, n: nat) returns (p : real) ensures p == power(x, n) { if n == 0 { return 1.0; } else if n == 1 { return x; } else if n % 2 == 0 { productOfPowers(x, n/2, n/2); // recall lemma var temp := powerDC(x, n/2); return temp * temp; } else { productOfPowers(x, (n-1)/2, (n-1)/2); // recall lemma var temp := powerDC(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that the method power takes advantage of. // The property is proved by automatic induction on 'a'. lemma {:induction a} productOfPowers(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { } // A few test cases (checked statically by Dafny). method testPowerDC() { var p1 := powerDC( 2.0, 5); assert p1 == 32.0; var p2 := powerDC(-2.0, 2); assert p2 == 4.0; var p3 := powerDC(-2.0, 1); assert p3 == -2.0; var p4 := powerDC(-2.0, 0); assert p4 == 1.0; var p5 := powerDC( 0.0, 0); assert p5 == 1.0; }
/* * Formal verification of an O(log n) algorithm to calculate the natural power of a real number (x^n), * illustrating the usage of lemmas and automatic induction in Dafny. * J. Pascoal Faria, FEUP, Jan/2022. */ // Recursive definition of x^n in functional style, with time and space complexity O(n). function power(x: real, n: nat) : real { if n == 0 then 1.0 else x * power(x, n-1) } // Computation of x^n in time and space O(log n). method powerDC(x: real, n: nat) returns (p : real) ensures p == power(x, n) { if n == 0 { return 1.0; } else if n == 1 { return x; } else if n % 2 == 0 { productOfPowers(x, n/2, n/2); // recall lemma var temp := powerDC(x, n/2); return temp * temp; } else { productOfPowers(x, (n-1)/2, (n-1)/2); // recall lemma var temp := powerDC(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that the method power takes advantage of. // The property is proved by automatic induction on 'a'. lemma {:induction a} productOfPowers(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { } // A few test cases (checked statically by Dafny). method testPowerDC() { var p1 := powerDC( 2.0, 5); assert p1 == 32.0; var p2 := powerDC(-2.0, 2); assert p2 == 4.0; var p3 := powerDC(-2.0, 1); assert p3 == -2.0; var p4 := powerDC(-2.0, 0); assert p4 == 1.0; var p5 := powerDC( 0.0, 0); assert p5 == 1.0; }
DafnyProjects_tmp_tmp2acw_s4s_Power.dfy
0.7191
124
124
Dafny program: 124
/** * Proves the correctness of a "raw" array sorting algorithm that swaps elements out of order, chosen randomly. * FEUP, MFES, 2020/21. */ // Type of each array element; can be any type supporting comparision operators. type T = int // Checks if array 'a' is sorted by non-descending order. ghost predicate sorted(a: array<T>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Obtains the set of all inversions in an array 'a', i.e., // the pairs of indices i, j such that i < j and a[i] > a[j]. ghost function inversions(a: array<T>): set<(nat, nat)> reads a { set i, j | 0 <= i < j < a.Length && a[i] > a[j] :: (i, j) } // Sorts an array by simply swapping elements out of order, chosen randomly. method rawsort(a: array<T>) modifies a ensures sorted(a) && multiset(a[..]) == multiset(old(a[..])) { if i, j :| 0 <= i < j < a.Length && a[i] > a[j] { ghost var bef := inversions(a); // inversions before swapping a[i], a[j] := a[j], a[i]; // swap ghost var aft := inversions(a); // inversions after swapping ghost var aft2bef := map p | p in aft :: // maps inversions in 'aft' to 'bef' (if p.0 == i && p.1 > j then j else if p.0 == j then i else p.0, if p.1 == i then j else if p.1 == j && p.0 < i then i else p.1); mappingProp(aft, bef, (i, j), aft2bef); // recall property implying |aft| < |bef| rawsort(a); // proceed recursivelly } } // States and proves (by induction) the following property: given sets 'a' and 'b' and an injective // and non-surjective mapping 'm' from elements in 'a' to elements in 'b', then |a| < |b|. // To facilitate the proof, it is given an element 'k' in 'b' that is not an image of elements in 'a'. lemma mappingProp<T1, T2>(a: set<T1>, b: set<T2>, k: T2, m: map<T1, T2>) requires k in b requires forall x :: x in a ==> x in m && m[x] in b - {k} requires forall x, y :: x in a && y in a && x != y ==> m[x] != m[y] ensures |a| < |b| { if x :| x in a { mappingProp(a - {x}, b - {m[x]}, k, m); } } method testRawsort() { var a : array<T> := new T[] [3, 5, 1]; rawsort(a); }
/** * Proves the correctness of a "raw" array sorting algorithm that swaps elements out of order, chosen randomly. * FEUP, MFES, 2020/21. */ // Type of each array element; can be any type supporting comparision operators. type T = int // Checks if array 'a' is sorted by non-descending order. ghost predicate sorted(a: array<T>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Obtains the set of all inversions in an array 'a', i.e., // the pairs of indices i, j such that i < j and a[i] > a[j]. ghost function inversions(a: array<T>): set<(nat, nat)> reads a { set i, j | 0 <= i < j < a.Length && a[i] > a[j] :: (i, j) } // Sorts an array by simply swapping elements out of order, chosen randomly. method rawsort(a: array<T>) modifies a ensures sorted(a) && multiset(a[..]) == multiset(old(a[..])) decreases |inversions(a)| { if i, j :| 0 <= i < j < a.Length && a[i] > a[j] { ghost var bef := inversions(a); // inversions before swapping a[i], a[j] := a[j], a[i]; // swap ghost var aft := inversions(a); // inversions after swapping ghost var aft2bef := map p | p in aft :: // maps inversions in 'aft' to 'bef' (if p.0 == i && p.1 > j then j else if p.0 == j then i else p.0, if p.1 == i then j else if p.1 == j && p.0 < i then i else p.1); mappingProp(aft, bef, (i, j), aft2bef); // recall property implying |aft| < |bef| rawsort(a); // proceed recursivelly } } // States and proves (by induction) the following property: given sets 'a' and 'b' and an injective // and non-surjective mapping 'm' from elements in 'a' to elements in 'b', then |a| < |b|. // To facilitate the proof, it is given an element 'k' in 'b' that is not an image of elements in 'a'. lemma mappingProp<T1, T2>(a: set<T1>, b: set<T2>, k: T2, m: map<T1, T2>) requires k in b requires forall x :: x in a ==> x in m && m[x] in b - {k} requires forall x, y :: x in a && y in a && x != y ==> m[x] != m[y] ensures |a| < |b| { if x :| x in a { mappingProp(a - {x}, b - {m[x]}, k, m); } } method testRawsort() { var a : array<T> := new T[] [3, 5, 1]; assert a[..] == [3, 5, 1]; rawsort(a); assert a[..] == [1, 3, 5]; }
DafnyProjects_tmp_tmp2acw_s4s_RawSort.dfy
2.1152
125
125
Dafny program: 125
/* * Formal verification of a simple algorithm to find the maximum value in an array. * FEUP, MIEIC, MFES, 2020/21. */ // Finds the maximum value in a non-empty array. method findMax(a: array<real>) returns (max: real) requires a.Length > 0 ensures exists k :: 0 <= k < a.Length && max == a[k] ensures forall k :: 0 <= k < a.Length ==> max >= a[k] { max := a[0]; for i := 1 to a.Length { if (a[i] > max) { max := a[i]; } } } // Test cases checked statically. method testFindMax() { var a1 := new real[3] [1.0, 2.0, 3.0]; // sorted asc var m1 := findMax(a1); var a2 := new real[3] [3.0, 2.0, 1.0]; // sorted desc var m2 := findMax(a2); var a3 := new real[3] [2.0, 3.0, 1.0]; // unsorted var m3 := findMax(a3); var a4 := new real[3] [1.0, 2.0, 2.0]; // duplicates var m4 := findMax(a4); var a5 := new real[1] [1.0]; // single element var m5 := findMax(a5); var a6 := new real[3] [1.0, 1.0, 1.0]; // all equal var m6 := findMax(a6); }
/* * Formal verification of a simple algorithm to find the maximum value in an array. * FEUP, MIEIC, MFES, 2020/21. */ // Finds the maximum value in a non-empty array. method findMax(a: array<real>) returns (max: real) requires a.Length > 0 ensures exists k :: 0 <= k < a.Length && max == a[k] ensures forall k :: 0 <= k < a.Length ==> max >= a[k] { max := a[0]; for i := 1 to a.Length invariant exists k :: 0 <= k < i && max == a[k] invariant forall k :: 0 <= k < i ==> max >= a[k] { if (a[i] > max) { max := a[i]; } } } // Test cases checked statically. method testFindMax() { var a1 := new real[3] [1.0, 2.0, 3.0]; // sorted asc var m1 := findMax(a1); assert m1 == a1[2] == 3.0; var a2 := new real[3] [3.0, 2.0, 1.0]; // sorted desc var m2 := findMax(a2); assert m2 == a2[0] == 3.0; var a3 := new real[3] [2.0, 3.0, 1.0]; // unsorted var m3 := findMax(a3); assert m3 == a3[1] == 3.0; var a4 := new real[3] [1.0, 2.0, 2.0]; // duplicates var m4 := findMax(a4); assert m4 == a4[1] == 2.0; var a5 := new real[1] [1.0]; // single element var m5 := findMax(a5); assert m5 == a5[0] == 1.0; var a6 := new real[3] [1.0, 1.0, 1.0]; // all equal var m6 := findMax(a6); assert m6 == a6[0] == 1.0; }
DafnyProjects_tmp_tmp2acw_s4s_findMax.dfy
0.911
126
126
Dafny program: 126
// MFES, Exam 8/Sept/20201, Exercise 5 // Computes the length (i) of the longest common prefix (initial subarray) // of two arrays a and b. method longestPrefix(a: array<int>, b: array <int>) returns (i: nat) ensures i <= a.Length && i <= b.Length ensures a[..i] == b[..i] ensures i < a.Length && i < b.Length ==> a[i] != b[i] { i := 0; while i < a.Length && i < b.Length && a[i] == b[i] { i := i + 1; } } // Test method with an example. method testLongestPrefix() { var a := new int[] [1, 3, 2, 4, 8]; var b := new int[] [1, 3, 3, 4]; var i := longestPrefix(a, b); }
// MFES, Exam 8/Sept/20201, Exercise 5 // Computes the length (i) of the longest common prefix (initial subarray) // of two arrays a and b. method longestPrefix(a: array<int>, b: array <int>) returns (i: nat) ensures i <= a.Length && i <= b.Length ensures a[..i] == b[..i] ensures i < a.Length && i < b.Length ==> a[i] != b[i] { i := 0; while i < a.Length && i < b.Length && a[i] == b[i] invariant i <= a.Length && i <= b.Length invariant a[..i] == b[..i] { i := i + 1; } } // Test method with an example. method testLongestPrefix() { var a := new int[] [1, 3, 2, 4, 8]; var b := new int[] [1, 3, 3, 4]; var i := longestPrefix(a, b); assert a[2] != b[2]; // to help Dafny prove next assertion assert i == 2; }
DafnyProjects_tmp_tmp2acw_s4s_longestPrefix.dfy
0.3562
127
127
Dafny program: 127
// Rearranges the elements in an array 'a' of natural numbers, // so that all odd numbers appear before all even numbers. method partitionOddEven(a: array<nat>) modifies a ensures multiset(a[..]) == multiset(old(a[..])) ensures ! exists i, j :: 0 <= i < j < a.Length && even(a[i]) && odd(a[j]) { var i := 0; // odd numbers are placed to the left of i var j := a.Length - 1; // even numbers are placed to the right of j while i <= j { if even(a[i]) && odd(a[j]) { a[i], a[j] := a[j], a[i]; } if odd(a[i]) { i := i + 1; } if even(a[j]) { j := j - 1; } } } predicate odd(n: nat) { n % 2 == 1 } predicate even(n: nat) { n % 2 == 0 } method testPartitionOddEven() { var a: array<nat> := new [] [1, 2, 3]; partitionOddEven(a); }
// Rearranges the elements in an array 'a' of natural numbers, // so that all odd numbers appear before all even numbers. method partitionOddEven(a: array<nat>) modifies a ensures multiset(a[..]) == multiset(old(a[..])) ensures ! exists i, j :: 0 <= i < j < a.Length && even(a[i]) && odd(a[j]) { var i := 0; // odd numbers are placed to the left of i var j := a.Length - 1; // even numbers are placed to the right of j while i <= j invariant 0 <= i <= j + 1 <= a.Length invariant multiset(a[..]) == old(multiset(a[..])) invariant forall k :: 0 <= k < i ==> odd(a[k]) invariant forall k :: j < k < a.Length ==> even(a[k]) { if even(a[i]) && odd(a[j]) { a[i], a[j] := a[j], a[i]; } if odd(a[i]) { i := i + 1; } if even(a[j]) { j := j - 1; } } } predicate odd(n: nat) { n % 2 == 1 } predicate even(n: nat) { n % 2 == 0 } method testPartitionOddEven() { var a: array<nat> := new [] [1, 2, 3]; assert a[..] == [1, 2, 3]; partitionOddEven(a); assert a[..] == [1, 3, 2] || a[..] == [3, 1, 2]; }
DafnyProjects_tmp_tmp2acw_s4s_partitionOddEven.dfy
0.9447
128
128
Dafny program: 128
method sqrt(x: real) returns (r: real) requires x >= 0.0 ensures r * r == x && r >= 0.0 method testSqrt() { var r := sqrt(4.0); //if (2.0 < r) { monotonicSquare(2.0, r); } if (r < 2.0) { monotonicSquare(r, 2.0); } } lemma monotonicMult(c: real, x: real, y: real) requires x < y && c > 0.0 ensures c * x < c * y {} lemma monotonicSquare(x: real, y: real) requires 0.0 < x < y ensures 0.0 < x * x < y * y { monotonicMult(x, x, y); }
method sqrt(x: real) returns (r: real) requires x >= 0.0 ensures r * r == x && r >= 0.0 method testSqrt() { var r := sqrt(4.0); //if (2.0 < r) { monotonicSquare(2.0, r); } if (r < 2.0) { monotonicSquare(r, 2.0); } assert r == 2.0; } lemma monotonicMult(c: real, x: real, y: real) requires x < y && c > 0.0 ensures c * x < c * y {} lemma monotonicSquare(x: real, y: real) requires 0.0 < x < y ensures 0.0 < x * x < y * y { monotonicMult(x, x, y); }
DafnyProjects_tmp_tmp2acw_s4s_sqrt.dfy
0.3199
132
132
Dafny program: 132
method LinearSearch<T>(a: array<T>, P: T -> bool) returns (n: int) ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < a.Length ==> ! P(a[i]) { n := 0; while n != a.Length { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch1<T>(a: array<T>, P: T -> bool, s1:seq<T>) returns (n: int) requires |s1| <= a.Length requires forall i:: 0<= i <|s1| ==> s1[i] == a[i] ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < |s1| ==> ! P(a[i]) { n := 0; while n != |s1| { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch2<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; position := 0; while n != |s1| { if data[|s1|-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method LinearSearch3<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && |s1| != 0 // ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; var n1 := |s1|; position := 0; while n != |s1| { if data[data.Length -n1 +n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; }
method LinearSearch<T>(a: array<T>, P: T -> bool) returns (n: int) ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < a.Length ==> ! P(a[i]) { n := 0; while n != a.Length decreases a.Length - n invariant 0 <= n <= a.Length invariant forall i :: 0 <= i < n ==> ! P(a[i]) invariant n == -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch1<T>(a: array<T>, P: T -> bool, s1:seq<T>) returns (n: int) requires |s1| <= a.Length requires forall i:: 0<= i <|s1| ==> s1[i] == a[i] ensures -1 <= n < a.Length ensures n == -1 || P(a[n]) ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) ensures n == -1 ==> forall i :: 0 <= i < |s1| ==> ! P(a[i]) { n := 0; while n != |s1| decreases |s1| - n invariant 0 <= n <= |s1| invariant forall i :: 0 <= i < n ==> ! P(a[i]) invariant n == -1 ==> forall i :: 0 <= i < n ==> ! P(a[i]) { if P(a[n]) { return; } n := n + 1; } n := -1; } method LinearSearch2<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; position := 0; while n != |s1| decreases |s1| - n invariant 0 <= n <= |s1| invariant position >= 1 ==> exists i::0 <=i < |s1| && data[i] == Element invariant forall i :: |s1|-1-n < i < |s1|==> data[i] != Element { if data[|s1|-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method LinearSearch3<T(==)>(data: array<T>, Element:T, s1:seq<T>) returns (position:int) requires |s1| <= data.Length requires forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i] ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && |s1| != 0 // ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element { var n := 0; var n1 := |s1|; position := 0; while n != |s1| decreases |s1| - n invariant 0 <= n <= |s1| invariant position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element invariant forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element invariant forall i :: |s1| - 1- n < i < |s1| -1 ==> s1[i] != Element { if data[data.Length -n1 +n] == Element { position := n + 1; assert data [data.Length-n1] == s1[|s1| -1]; assert data[data.Length -n1 +n] == s1[n1-1-n]; assert forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i]; assert forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element; assert forall i :: |s1| - 1 > i > |s1| -1 -n ==> s1[i] != Element; assert forall i:: data.Length - |s1| < i< data.Length-1 ==> data[i] == s1[data.Length-i-1]; return position; } n := n + 1; } position := -1; assert |s1| <= data.Length; assert |s1| != 0 ==> s1[0] == data[data.Length-1]; assert |s1| != 0 ==> data[data.Length-n1] == s1[|s1| -1]; assert forall i:: data.Length - |s1| < i< data.Length-1 ==> data[i] == s1[data.Length-i-1]; assert forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element; assert forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i]; assert forall i :: |s1| - 1 > i > |s1| -1 -n ==> s1[i] != Element; }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week4_tute_ex4.dfy
0.3072
133
133
Dafny program: 133
function Power(n:nat):nat { if n == 0 then 1 else 2 * Power(n-1) } method CalcPower(n:nat) returns (p:nat) ensures p == 2*n; { p := 2*n; } method ComputePower(n:nat) returns (p:nat) ensures p == Power(n) { p:=1; var i:=0; while i!=n { p:= CalcPower(p); i:=i+1; } }
function Power(n:nat):nat { if n == 0 then 1 else 2 * Power(n-1) } method CalcPower(n:nat) returns (p:nat) ensures p == 2*n; { p := 2*n; } method ComputePower(n:nat) returns (p:nat) ensures p == Power(n) { p:=1; var i:=0; while i!=n invariant 0 <= i <= n invariant p *Power(n-i) == Power(n) { p:= CalcPower(p); i:=i+1; } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week5_ComputePower.dfy
0.8177
134
134
Dafny program: 134
class TwoStacks<T(0)(==)> { //abstract state ghost var s1 :seq<T> ghost var s2 :seq<T> ghost const N :nat // maximum size of the stacks ghost var Repr : set<object> //concrete state var data: array<T> var n1: nat // number of elements in the stack 1 var n2: nat // number of elements in the stack 2 ghost predicate Valid() reads this,Repr ensures Valid() ==> this in Repr && |s1| + |s2| <= N && 0 <= |s1| <= N && 0 <=|s2| <= N { this in Repr && data in Repr && data.Length == N && 0 <= |s1| + |s2| <= N && 0 <=|s1| <= N && 0 <=|s2| <= N && (|s1| != 0 ==> forall i:: 0<= i < |s1| ==> s1[i] == data[i]) && (|s2| != 0 ==> forall i:: 0<= i < |s2| ==> s2[i] == data[data.Length-1-i]) && n1 == |s1| && n2 == |s2| } constructor (N: nat) ensures Valid() && fresh(Repr) ensures s1 == s2 == [] && this.N == N { s1,s2,this.N := [],[],N; data := new T[N]; n1, n2 := 0, 0; Repr := {this, data}; } method push1(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s1|) != N && old(|s1|) + old(|s2|) != N ==> s1 == old(s1) + [element]; ensures old(|s1|) == N ==> FullStatus == false ensures old(|s1|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == data.Length { FullStatus := false; }else { if n1 != data.Length && n1 + n2 != data.Length{ s1 := old(s1) + [element] ; data[n1] := element; n1 := n1 +1; FullStatus := true; }else{ FullStatus := false; } } } method push2(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s2|) != N && old(|s1|) + old(|s2|) != N ==> s2 == old(s2) + [element]; ensures old(|s2|) == N ==> FullStatus == false ensures old(|s2|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == data.Length { FullStatus := false; }else { if n2 != data.Length && n1 + n2 != data.Length{ s2 := old(s2) + [element] ; data[data.Length-1-n2] := element; n2 := n2 +1; FullStatus := true; }else{ FullStatus := false; } } } method pop1() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s1|) != 0 ==> s1 == old(s1[0..|s1|-1]) && EmptyStatus == true && PopedItem == old(s1[|s1|-1]) ensures old(|s1|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == 0 { EmptyStatus := false; PopedItem := *; } else{ s1 := old(s1[0..|s1|-1]); PopedItem := data[n1-1]; n1 := n1 -1; EmptyStatus := true; } } method pop2() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s2|) != 0 ==> s2 == old(s2[0..|s2|-1]) && EmptyStatus == true && PopedItem == old(s2[|s2|-1]) ensures old(|s2|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == 0 { EmptyStatus := false; PopedItem := *; } else{ s2 := old(s2[0..|s2|-1]); PopedItem := data[data.Length-n2]; n2 := n2 -1; EmptyStatus := true; } } method peek1() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty1() ==> EmptyStatus == false ensures !Empty1() ==> EmptyStatus == true && TopItem == s1[|s1|-1] ensures Valid() { if n1 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[n1-1]; EmptyStatus := true; } } method peek2() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty2() ==> EmptyStatus == false ensures !Empty2() ==> EmptyStatus == true && TopItem == s2[|s2|-1] ensures Valid() { if n2 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[data.Length-n2]; EmptyStatus := true; } } ghost predicate Empty1() requires Valid() reads this,Repr ensures Empty1() ==> |s1| == 0 ensures Valid() { |s1| == 0 && n1 == 0 } ghost predicate Empty2() reads this ensures Empty2() ==> |s2| == 0 { |s2| == 0 && n2 == 0 } method search1(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && !Empty1() ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element || Empty1() ensures Valid() { var n := 0; position := 0; while n != n1 { if data[n1-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method search3(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s2| && s2[i] == Element && !Empty2() // ensures position == -1 ==> forall i :: 0 <= i < |s2| ==> s2[i] != Element || Empty2() ensures Valid() { position := 0; var n := 0; while n != n2 { if data[data.Length - n2 + n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } }
class TwoStacks<T(0)(==)> { //abstract state ghost var s1 :seq<T> ghost var s2 :seq<T> ghost const N :nat // maximum size of the stacks ghost var Repr : set<object> //concrete state var data: array<T> var n1: nat // number of elements in the stack 1 var n2: nat // number of elements in the stack 2 ghost predicate Valid() reads this,Repr ensures Valid() ==> this in Repr && |s1| + |s2| <= N && 0 <= |s1| <= N && 0 <=|s2| <= N { this in Repr && data in Repr && data.Length == N && 0 <= |s1| + |s2| <= N && 0 <=|s1| <= N && 0 <=|s2| <= N && (|s1| != 0 ==> forall i:: 0<= i < |s1| ==> s1[i] == data[i]) && (|s2| != 0 ==> forall i:: 0<= i < |s2| ==> s2[i] == data[data.Length-1-i]) && n1 == |s1| && n2 == |s2| } constructor (N: nat) ensures Valid() && fresh(Repr) ensures s1 == s2 == [] && this.N == N { s1,s2,this.N := [],[],N; data := new T[N]; n1, n2 := 0, 0; Repr := {this, data}; } method push1(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s1|) != N && old(|s1|) + old(|s2|) != N ==> s1 == old(s1) + [element]; ensures old(|s1|) == N ==> FullStatus == false ensures old(|s1|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == data.Length { FullStatus := false; }else { if n1 != data.Length && n1 + n2 != data.Length{ s1 := old(s1) + [element] ; data[n1] := element; n1 := n1 +1; FullStatus := true; }else{ FullStatus := false; } } } method push2(element:T) returns (FullStatus:bool) requires Valid() modifies Repr ensures old(|s2|) != N && old(|s1|) + old(|s2|) != N ==> s2 == old(s2) + [element]; ensures old(|s2|) == N ==> FullStatus == false ensures old(|s2|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == data.Length { FullStatus := false; }else { if n2 != data.Length && n1 + n2 != data.Length{ s2 := old(s2) + [element] ; data[data.Length-1-n2] := element; n2 := n2 +1; FullStatus := true; }else{ FullStatus := false; } } } method pop1() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s1|) != 0 ==> s1 == old(s1[0..|s1|-1]) && EmptyStatus == true && PopedItem == old(s1[|s1|-1]) ensures old(|s1|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n1 == 0 { EmptyStatus := false; PopedItem := *; } else{ s1 := old(s1[0..|s1|-1]); PopedItem := data[n1-1]; n1 := n1 -1; EmptyStatus := true; } } method pop2() returns (EmptyStatus:bool, PopedItem:T) requires Valid() modifies Repr ensures old(|s2|) != 0 ==> s2 == old(s2[0..|s2|-1]) && EmptyStatus == true && PopedItem == old(s2[|s2|-1]) ensures old(|s2|) == 0 ==> EmptyStatus == false ensures Valid() && fresh(Repr - old(Repr)) { if n2 == 0 { EmptyStatus := false; PopedItem := *; } else{ s2 := old(s2[0..|s2|-1]); PopedItem := data[data.Length-n2]; n2 := n2 -1; EmptyStatus := true; } } method peek1() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty1() ==> EmptyStatus == false ensures !Empty1() ==> EmptyStatus == true && TopItem == s1[|s1|-1] ensures Valid() { if n1 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[n1-1]; EmptyStatus := true; } } method peek2() returns (EmptyStatus:bool, TopItem:T) requires Valid() ensures Empty2() ==> EmptyStatus == false ensures !Empty2() ==> EmptyStatus == true && TopItem == s2[|s2|-1] ensures Valid() { if n2 == 0 { EmptyStatus := false; TopItem := *; } else { TopItem := data[data.Length-n2]; EmptyStatus := true; } } ghost predicate Empty1() requires Valid() reads this,Repr ensures Empty1() ==> |s1| == 0 ensures Valid() { |s1| == 0 && n1 == 0 } ghost predicate Empty2() reads this ensures Empty2() ==> |s2| == 0 { |s2| == 0 && n2 == 0 } method search1(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && !Empty1() ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element || Empty1() ensures Valid() { var n := 0; position := 0; while n != n1 decreases |s1| - n invariant Valid() invariant 0 <= n <= |s1| invariant position >= 1 ==> exists i::0 <= i < |s1| && s1[i] == Element invariant forall i :: |s1|-1-n < i < |s1|==> s1[i] != Element { if data[n1-1-n] == Element { position := n + 1; return position; } n := n + 1; } position := -1; } method search3(Element:T) returns (position:int) requires Valid() ensures position == -1 || position >= 1 ensures position >= 1 ==> exists i::0 <=i < |s2| && s2[i] == Element && !Empty2() // ensures position == -1 ==> forall i :: 0 <= i < |s2| ==> s2[i] != Element || Empty2() ensures Valid() { position := 0; var n := 0; while n != n2 decreases |s2| - n invariant 0 <= n <= |s2| invariant Valid() invariant position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element invariant forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element invariant forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element { if data[data.Length - n2 + n] == Element { position := n + 1; assert data[data.Length -n2 +n] == s2[n2-1-n]; assert position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element; assert forall i:: data.Length - |s2| < i< data.Length-1 ==> data[i] == s2[data.Length-i-1]; assert forall i:: 0 <= i < |s2| ==> s2[i] == data[data.Length-i-1]; assert forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element; assert forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element; return position; } n := n + 1; } position := -1; assert position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element; assert forall i:: data.Length - |s2| < i< data.Length-1 ==> data[i] == s2[data.Length-i-1]; assert forall i:: 0 <= i < |s2| ==> s2[i] == data[data.Length-i-1]; assert forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element; assert forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element; } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_a3 copy 2.dfy
0.5176
137
137
Dafny program: 137
class ExtensibleArray<T(0)> { // abstract state ghost var Elements: seq<T> ghost var Repr: set<object> //concrete state var front: array?<T> var depot: ExtensibleArray?<array<T>> var length: int // number of elements var M: int // number of elements in depot ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr { // Abstraction relation: Repr this in Repr && (front != null ==> front in Repr) && (depot != null ==> depot in Repr && depot.Repr <= Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] in Repr) && // Standard concrete invariants: Aliasing (depot != null ==> this !in depot.Repr && front !in depot.Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] !in depot.Repr && depot.Elements[j] != front && forall k :: 0 <= k < |depot.Elements| && k != j ==> depot.Elements[j] != depot.Elements[k]) && // Concrete state invariants (front != null ==> front.Length == 256) && (depot != null ==> depot.Valid() && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j].Length == 256) && (length == M <==> front == null) && M == (if depot == null then 0 else 256 * |depot.Elements|) && // Abstraction relation: Elements length == |Elements| && M <= |Elements| < M + 256 && (forall i :: 0 <= i < M ==> Elements[i] == depot.Elements[i / 256][i % 256]) && (forall i :: M <= i < length ==> Elements[i] == front[i - M]) } constructor () ensures Valid() && fresh(Repr) && Elements == [] { front, depot := null, null; length, M := 0, 0; Elements, Repr := [], {this}; } function Get(i: int): T requires Valid() && 0 <= i < |Elements| ensures Get(i) == Elements[i] reads Repr { if M <= i then front[i - M] else depot.Get(i/256)[i%256] } method Set(i: int, t: T) requires Valid() && 0 <= i < |Elements| modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements)[i := t] { if M <= i { front[i - M] := t; } else { depot.Get(i/256)[i%256] := t; } Elements := Elements[i := t]; } method Add(t: T) requires Valid() modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements) + [t] { if front == null { front := new T[256]; Repr := Repr + {front}; } front[length-M] := t; length := length + 1; Elements := Elements + [t]; if length == M + 256 { if depot == null { depot := new ExtensibleArray(); } depot.Add(front); Repr := Repr + depot.Repr; M := M + 256; front := null; } } }
class ExtensibleArray<T(0)> { // abstract state ghost var Elements: seq<T> ghost var Repr: set<object> //concrete state var front: array?<T> var depot: ExtensibleArray?<array<T>> var length: int // number of elements var M: int // number of elements in depot ghost predicate Valid() decreases Repr +{this} reads this, Repr ensures Valid() ==> this in Repr { // Abstraction relation: Repr this in Repr && (front != null ==> front in Repr) && (depot != null ==> depot in Repr && depot.Repr <= Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] in Repr) && // Standard concrete invariants: Aliasing (depot != null ==> this !in depot.Repr && front !in depot.Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] !in depot.Repr && depot.Elements[j] != front && forall k :: 0 <= k < |depot.Elements| && k != j ==> depot.Elements[j] != depot.Elements[k]) && // Concrete state invariants (front != null ==> front.Length == 256) && (depot != null ==> depot.Valid() && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j].Length == 256) && (length == M <==> front == null) && M == (if depot == null then 0 else 256 * |depot.Elements|) && // Abstraction relation: Elements length == |Elements| && M <= |Elements| < M + 256 && (forall i :: 0 <= i < M ==> Elements[i] == depot.Elements[i / 256][i % 256]) && (forall i :: M <= i < length ==> Elements[i] == front[i - M]) } constructor () ensures Valid() && fresh(Repr) && Elements == [] { front, depot := null, null; length, M := 0, 0; Elements, Repr := [], {this}; } function Get(i: int): T requires Valid() && 0 <= i < |Elements| ensures Get(i) == Elements[i] reads Repr { if M <= i then front[i - M] else depot.Get(i/256)[i%256] } method Set(i: int, t: T) requires Valid() && 0 <= i < |Elements| modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements)[i := t] { if M <= i { front[i - M] := t; } else { depot.Get(i/256)[i%256] := t; } Elements := Elements[i := t]; } method Add(t: T) requires Valid() modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements) + [t] decreases |Elements| { if front == null { front := new T[256]; Repr := Repr + {front}; } front[length-M] := t; length := length + 1; Elements := Elements + [t]; if length == M + 256 { if depot == null { depot := new ExtensibleArray(); } depot.Add(front); Repr := Repr + depot.Repr; M := M + 256; front := null; } } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week10_ExtensibleArray.dfy
1.1832
138
138
Dafny program: 138
ghost function Hash(s:string):int { SumChars(s) % 137 } ghost function SumChars(s: string):int { if |s| == 0 then 0 else s[|s| - 1] as int + SumChars(s[..|s| -1]) } class CheckSumCalculator{ var data: string var cs:int ghost predicate Valid() reads this { cs == Hash(data) } constructor () ensures Valid() && data == "" { data, cs := "", 0; } method Append(d:string) requires Valid() modifies this ensures Valid() && data == old(data) + d { var i := 0; while i != |d| { cs := (cs + d[i] as int) % 137; data := data + [d[i]]; i := i +1; } } function GetData(): string requires Valid() reads this ensures Hash(GetData()) == Checksum() { data } function Checksum(): int requires Valid() reads this ensures Checksum() == Hash(data) { cs } } method Main() { /* var m:= new CheckSumCalculator(); m.Append("g"); m.Append("Grass"); var c:= m.Checksum(); var g:= m.GetData(); print "(m.cs)Checksum is " ,m.cs,"\n"; print "(c)Checksum is " ,c,"\n"; print "(m.data)Checksum is " ,m.data,"\n"; print "(g)Checksum is " ,g,"\n"; var tmpStr := "abcde"; var tmpStrOne := "LLLq"; var tmpSet := {'a','c'}; var tmpFresh := {'a','b'}; var tmpnum := 1; print "tmp is ", tmpSet - tmpFresh; var newArray := new int[10]; newArray[0]:= 0; */ var newSeq := ['a','b','c','d','e','f','g','h']; var newSeqTwo := ['h','g','f','e','d','c','b','a']; var newSet : set<int>; newSet := {1,2,3,4,5}; var newSetTwo := {6,7,8,9,10}; print "element is newset ", newSet,"\n"; var newArray := new int [99]; newArray[0] := 99; newArray[1] := 2; print "element is ? ", |[newArray]|,"\n"; var tmpSet := {'a','c'}; var tmpFresh := {'c'}; print "tmp is ", tmpSet - tmpFresh; var newMap := map[]; newMap := newMap[1:=2]; var nnewMap := map[3:=444]; print "keys is ",newMap.Keys,newMap.Values; print "value is", nnewMap.Keys,nnewMap.Values; }
ghost function Hash(s:string):int { SumChars(s) % 137 } ghost function SumChars(s: string):int { if |s| == 0 then 0 else s[|s| - 1] as int + SumChars(s[..|s| -1]) } class CheckSumCalculator{ var data: string var cs:int ghost predicate Valid() reads this { cs == Hash(data) } constructor () ensures Valid() && data == "" { data, cs := "", 0; } method Append(d:string) requires Valid() modifies this ensures Valid() && data == old(data) + d { var i := 0; while i != |d| invariant 0<= i <= |d| invariant Valid() invariant data == old(data) + d[..i] { cs := (cs + d[i] as int) % 137; data := data + [d[i]]; i := i +1; } } function GetData(): string requires Valid() reads this ensures Hash(GetData()) == Checksum() { data } function Checksum(): int requires Valid() reads this ensures Checksum() == Hash(data) { cs } } method Main() { /* var m:= new CheckSumCalculator(); m.Append("g"); m.Append("Grass"); var c:= m.Checksum(); var g:= m.GetData(); print "(m.cs)Checksum is " ,m.cs,"\n"; print "(c)Checksum is " ,c,"\n"; print "(m.data)Checksum is " ,m.data,"\n"; print "(g)Checksum is " ,g,"\n"; var tmpStr := "abcde"; var tmpStrOne := "LLLq"; var tmpSet := {'a','c'}; var tmpFresh := {'a','b'}; var tmpnum := 1; print "tmp is ", tmpSet - tmpFresh; var newArray := new int[10]; newArray[0]:= 0; */ var newSeq := ['a','b','c','d','e','f','g','h']; var newSeqTwo := ['h','g','f','e','d','c','b','a']; var newSet : set<int>; newSet := {1,2,3,4,5}; var newSetTwo := {6,7,8,9,10}; print "element is newset ", newSet,"\n"; var newArray := new int [99]; newArray[0] := 99; newArray[1] := 2; print "element is ? ", |[newArray]|,"\n"; var tmpSet := {'a','c'}; var tmpFresh := {'c'}; print "tmp is ", tmpSet - tmpFresh; var newMap := map[]; newMap := newMap[1:=2]; var nnewMap := map[3:=444]; print "keys is ",newMap.Keys,newMap.Values; print "value is", nnewMap.Keys,nnewMap.Values; }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week8_CheckSumCalculator.dfy
0.7834
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
28