test_ID
stringlengths
3
3
test_file
stringlengths
14
119
ground_truth
stringlengths
70
28.7k
hints_removed
stringlengths
58
28.7k
100
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBubbleSort.dfy
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; } }
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; } }
101
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseReplace.dfy
method replace(v:array<int>, x:int, y:int) modifies v ensures forall k::0<=k<old(v.Length) && old(v[k])==x ==> v[k]==y ensures forall k::0<=k<old(v.Length) && old(v[k])!=x ==> v[k]==old(v[k]) { var i:=0; while(i<v.Length) decreases v.Length - i invariant 0<=i<=v.Length invariant forall k::0<=k<i && old(v[k])==x ==> v[k]==y invariant forall k::i<=k<v.Length ==> v[k] == old(v[k]) invariant forall k::0<=k<i && old(v[k])!=x ==> v[k]==old(v[k]) { if(v[i]==x){ v[i]:=y; } i:=i+1; } }
method replace(v:array<int>, x:int, y:int) modifies v ensures forall k::0<=k<old(v.Length) && old(v[k])==x ==> v[k]==y ensures forall k::0<=k<old(v.Length) && old(v[k])!=x ==> v[k]==old(v[k]) { var i:=0; while(i<v.Length) { if(v[i]==x){ v[i]:=y; } i:=i+1; } }
102
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseSelSort.dfy
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; } } }
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; } } }
103
Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseSeparate.dfy
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; } } }
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; } } }
104
Dafny-Exercises_tmp_tmpjm75muf__Session8Exercises_ExerciseInsertionSort.dfy
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; } }
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; } }
105
Dafny-Exercises_tmp_tmpjm75muf__Session9Exercises_ExerciseSeqMaxSum.dfy
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; }
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; }
106
Dafny-Grind75_tmp_tmpsxfz3i4r_problems_twoSum.dfy
/* https://leetcode.com/problems/two-sum/ function twoSum(nums: number[], target: number): number[] { const n = nums.length; for(let i = 0; i < n; i++) { for(let k = i+1; k < n; k++) { if(nums[i] + nums[k] == target) return [i,k]; } } }; */ predicate summingPair(i: nat, j: nat, nums: seq<int>, target: int) requires i < |nums| requires j < |nums| { i != j && nums[i] + nums[j] == target } method twoSum(nums: seq<int>, target: int) returns (pair: (nat, nat)) requires exists i:nat,j:nat :: i < j < |nums| && summingPair(i, j, nums, target) && forall l: nat, m: nat :: l < m < |nums| && l != i && m != j ==> !summingPair(l, m, nums, target) ensures 0 <= pair.0 < |nums| && 0 <= pair.1 < |nums| && summingPair(pair.0, pair.1, nums, target) { pair := (0,0); var i: nat := 0; while i < |nums| invariant i <= |nums| invariant forall z: nat, j: nat :: 0 <= z < i && z+1 <= j < |nums| ==> !summingPair(z, j, nums, target) { var k: nat := i + 1; while k < |nums| invariant i + 1 <= k <= |nums| // invariant forall q: nat :: i+1 <= q < k < |nums| ==> !summingPair(i,q, nums, target) //this fails to verify invariant forall q: nat :: i+1 <= q < k <= |nums| ==> !summingPair(i,q, nums, target) //this verifies { // assert i < k < |nums|; if nums[i] + nums[k] == target { pair := (i,k); return pair; } k := k + 1; } i := i + 1; } }
/* https://leetcode.com/problems/two-sum/ function twoSum(nums: number[], target: number): number[] { const n = nums.length; for(let i = 0; i < n; i++) { for(let k = i+1; k < n; k++) { if(nums[i] + nums[k] == target) return [i,k]; } } }; */ predicate summingPair(i: nat, j: nat, nums: seq<int>, target: int) requires i < |nums| requires j < |nums| { i != j && nums[i] + nums[j] == target } method twoSum(nums: seq<int>, target: int) returns (pair: (nat, nat)) requires exists i:nat,j:nat :: i < j < |nums| && summingPair(i, j, nums, target) && forall l: nat, m: nat :: l < m < |nums| && l != i && m != j ==> !summingPair(l, m, nums, target) ensures 0 <= pair.0 < |nums| && 0 <= pair.1 < |nums| && summingPair(pair.0, pair.1, nums, target) { pair := (0,0); var i: nat := 0; while i < |nums| { var k: nat := i + 1; while k < |nums| // invariant forall q: nat :: i+1 <= q < k < |nums| ==> !summingPair(i,q, nums, target) //this fails to verify { // assert i < k < |nums|; if nums[i] + nums[k] == target { pair := (i,k); return pair; } k := k + 1; } i := i + 1; } }
107
Dafny-Practice_tmp_tmphnmt4ovh_BST.dfy
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 {}
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 {}
108
Dafny-Practice_tmp_tmphnmt4ovh_Pattern Matching.dfy
method {:verify true} FindAllOccurrences(text: string, pattern: string) returns (offsets: set<nat>) ensures forall i :: i in offsets ==> i + |pattern| <= |text| ensures forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets) { offsets := {}; var i:int := 0; // no pattern in text at all. if |pattern| > |text| { assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); return offsets; } //all offsets are offsets of pattern/ if pattern == "" { while i < |text| invariant 0 <= i <=|text| invariant forall j :: 0 <= j < i ==> (text[j..j+|pattern|] == pattern <==> j in offsets) invariant forall j :: j in offsets ==> j + |pattern| <= |text| { offsets := offsets + {i}; i:=i+1; } offsets := offsets + {|text|}; assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); return offsets; } var pattern_hash: int := RecursiveSumDown(pattern); var text_hash: int := RecursiveSumDown(text[..|pattern|]); assert text_hash == RecursiveSumDown(text[..|pattern|]); if pattern_hash == text_hash{ if text[..|pattern|] == pattern { offsets := offsets + {0}; } } else { LemmaRabinKarp(text[..|pattern|], pattern, text_hash, pattern_hash); } while i < |text| - |pattern| invariant 0 <= i <= |text| - |pattern| invariant text_hash == RecursiveSumDown(text[i..i + |pattern|]) invariant forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets) invariant forall i :: i in offsets ==> i + |pattern| <= |text| invariant forall k :: i < k ==> (k in offsets) == false decreases |text| - |pattern| - i { assert text_hash == RecursiveSumDown(text[i..i + |pattern|]); assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); //updating text hash var old_text_hash := text_hash; assert old_text_hash == RecursiveSumDown(text[i..i + |pattern|]); var left_letter_as_int := text[i] as int; var right_new_letter_as_int := text[i+|pattern|] as int; text_hash := text_hash - left_letter_as_int + right_new_letter_as_int; //updating i assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert text_hash == old_text_hash - text[i] as int + text[i+|pattern|] as int; assert old_text_hash == RecursiveSumDown(text[i..i + |pattern|]); i := i + 1; assert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); assert forall k :: 0 <= k < i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int; //checking hash equality if pattern_hash == text_hash{ if text[i..i + |pattern|] == pattern { assert (text[i..i + |pattern|] == pattern); offsets := offsets + {i}; assert (i in offsets); assert text[i..i+|pattern|] == pattern <== i in offsets; assert text[i..i+|pattern|] == pattern ==> i in offsets; } assert pattern_hash == RecursiveSumDown(pattern); assert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int; assert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); assert text_hash == RecursiveSumDown(text[i..i+|pattern|]); } else{ assert text_hash != pattern_hash; assert pattern_hash == RecursiveSumDown(pattern); assert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int; assert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); assert text_hash == RecursiveSumDown(text[i..i+|pattern|]); LemmaRabinKarp(text[i..i+|pattern|], pattern, text_hash, pattern_hash); assert text[i..i+|pattern|] == pattern ==> i in offsets; assert (i in offsets) == false; assert text[i..i+|pattern|] == pattern <== i in offsets; } assert text[i..i+|pattern|] == pattern ==> i in offsets; assert text[i..i+|pattern|] == pattern <== i in offsets; Lemma2Sides(text, pattern, i, offsets); //=> assert text[i..i+|pattern|] == pattern <==> i in offsets; assert forall k :: 0 <= k < i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); //=> assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert text_hash == RecursiveSumDown(text[i..i+|pattern|]); } assert 0 <= i <= |text| - |pattern|; assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall k :: i < k ==> (k in offsets) == false; assert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets); assert i >= |text| - |pattern|; //=> assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); assert forall i :: i in offsets ==> i + |pattern| <= |text|; assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets); } function RecursiveSumDown(str: string): int decreases |str| { if str == "" then 0 else str[|str|-1] as int +RecursiveSumDown(str[..|str|-1]) } function RecursiveSumUp(str: string): int decreases |str| { if str == "" then 0 else str[0] as int + RecursiveSumUp(str[1..]) } lemma {:verify true}LemmaRabinKarp(t_sub:string, pattern:string, text_hash:int, pattern_hash:int) requires text_hash != pattern_hash requires pattern_hash == RecursiveSumDown(pattern) requires text_hash == RecursiveSumDown(t_sub) ensures t_sub[..] != pattern[..] {} lemma Lemma2Sides(text: string, pattern: string, i: nat, offsets: set<nat>) requires 0 <= i <= |text| - |pattern| requires (text[i..i+|pattern|] == pattern ==> i in offsets) requires (text[i..i+|pattern|] == pattern <== i in offsets) ensures (text[i..i+|pattern|] == pattern <==> i in offsets) {} lemma LemmaHashEqualty(text_hash : int, text: string, i: nat, old_text_hash: int, pattern: string) requires 0 < i <= |text| - |pattern| requires text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int requires old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); ensures text_hash == RecursiveSumDown(text[i..i+|pattern|]) { assert 0 < i <= |text| - |pattern|; assert 0 <= i - 1 < |text| - |pattern|; ghost var temp_val := old_text_hash + text[i - 1 + |pattern|] as int; assert text_hash == old_text_hash + text[i - 1 + |pattern|] as int - text[i - 1] as int; //=> assert text_hash == temp_val - text[i - 1] as int; assert 0 <= |pattern| < |text[i - 1..]|; ghost var str := text[i - 1..]; assert str[..|pattern|] == text[i - 1 .. i - 1 + |pattern|]; assert old_text_hash == RecursiveSumDown(str[..|pattern|]); LemmaAddingOneIndex(str, |pattern|, old_text_hash); assert old_text_hash + str[|pattern|] as int == RecursiveSumDown(str[..|pattern|+1]); assert str[..|pattern|+1] == text[i - 1..i - 1 + |pattern| + 1]; //=> assert old_text_hash + text[i - 1 + |pattern|] as int == RecursiveSumDown(text[i - 1..i - 1 + |pattern| + 1]); assert temp_val == old_text_hash + text[i - 1 + |pattern|] as int; //=> assert temp_val == RecursiveSumDown(text[i - 1..i - 1 + |pattern| + 1]); assert temp_val == RecursiveSumDown(text[i - 1..i + |pattern|]); PrependSumUp(text[i - 1..i + |pattern|]); assert RecursiveSumUp(text[i - 1..i + |pattern|]) == text[i - 1] as int + RecursiveSumUp(text[i..i + |pattern|]); EquivalentSumDefinitions(text[i - 1..i + |pattern|]); EquivalentSumDefinitions(text[i..i + |pattern|]); //=> assert RecursiveSumUp(text[i - 1..i + |pattern|]) == RecursiveSumDown(text[i - 1..i + |pattern|]); assert RecursiveSumUp(text[i..i + |pattern|]) == RecursiveSumDown(text[i..i + |pattern|]); //=> assert RecursiveSumDown(text[i - 1..i + |pattern|]) == text[i - 1] as int + RecursiveSumDown(text[i..i + |pattern|]); //=> assert RecursiveSumDown(text[i - 1..i + |pattern|]) - text[i - 1] as int == RecursiveSumDown(text[i..i + |pattern|]); assert text_hash == temp_val - text[i - 1] as int; assert temp_val == RecursiveSumDown(text[i - 1..i + |pattern|]); assert text_hash == RecursiveSumDown(text[i - 1..i + |pattern|]) - text[i - 1] as int; //=> assert text_hash == RecursiveSumDown(text[i..i + |pattern|]); } lemma LemmaAddingOneIndex(str: string, i: nat, sum: int) requires 0 <= i < |str| && sum == RecursiveSumDown(str[..i]) ensures 0 <= i+1 <= |str| && sum + str[i] as int == RecursiveSumDown(str[..i+1]) { var str1 := str[..i+1]; calc { RecursiveSumDown(str[..i+1]); == // def. if str1 == [] then 0 else str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert str1 != []; } // simplification for a non-empty sequence str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert |str1|-1 == i; } str1[i] as int + RecursiveSumDown(str1[..i]); == { assert str1[..i] == str[..i]; } str[i] as int + RecursiveSumDown(str[..i]); == // inv. str[i] as int + sum; == sum + str[i] as int; } } lemma PrependSumUp(str: string) requires str != "" ensures RecursiveSumUp(str) == str[0] as int + RecursiveSumUp(str[1..]) { // directly from the definition of RecursiveSumUp (for a non-emty sequence) } lemma EquivalentSumDefinitions(str: string) ensures RecursiveSumDown(str) == RecursiveSumUp(str) decreases |str| { if |str| == 0 { assert str == ""; assert RecursiveSumDown([]) == 0 == RecursiveSumUp([]); } else if |str| == 1 { assert str == [str[0]]; assert RecursiveSumDown(str) == str[0] as int == RecursiveSumUp(str); } else { assert |str| >= 2; var first: char, mid: string, last:char := str[0], str[1..|str|-1], str[|str|-1]; assert str == [first] + mid + [last]; calc { RecursiveSumDown(str); == { assert str != [] && str[|str|-1] == last && str[..|str|-1] == [first] + mid; } last as int + RecursiveSumDown([first] + mid); == // arithmetic RecursiveSumDown([first] + mid) + last as int; == { EquivalentSumDefinitions([first] + mid); } // induction hypothesis RecursiveSumUp([first] + mid) + last as int; == { assert [first] + mid != []; } first as int + RecursiveSumUp(mid) + last as int; == { EquivalentSumDefinitions(mid); } // induction hypothesis first as int + RecursiveSumDown(mid) + last as int; == first as int + RecursiveSumDown(mid + [last]); == { EquivalentSumDefinitions(mid + [last]); } // induction hypothesis first as int + RecursiveSumUp(mid + [last]); == { assert str != [] && str[0] == first && str[1..] == mid + [last]; } RecursiveSumUp(str); } } }
method {:verify true} FindAllOccurrences(text: string, pattern: string) returns (offsets: set<nat>) ensures forall i :: i in offsets ==> i + |pattern| <= |text| ensures forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets) { offsets := {}; var i:int := 0; // no pattern in text at all. if |pattern| > |text| { return offsets; } //all offsets are offsets of pattern/ if pattern == "" { while i < |text| { offsets := offsets + {i}; i:=i+1; } offsets := offsets + {|text|}; return offsets; } var pattern_hash: int := RecursiveSumDown(pattern); var text_hash: int := RecursiveSumDown(text[..|pattern|]); if pattern_hash == text_hash{ if text[..|pattern|] == pattern { offsets := offsets + {0}; } } else { LemmaRabinKarp(text[..|pattern|], pattern, text_hash, pattern_hash); } while i < |text| - |pattern| { //updating text hash var old_text_hash := text_hash; var left_letter_as_int := text[i] as int; var right_new_letter_as_int := text[i+|pattern|] as int; text_hash := text_hash - left_letter_as_int + right_new_letter_as_int; //updating i i := i + 1; //checking hash equality if pattern_hash == text_hash{ if text[i..i + |pattern|] == pattern { offsets := offsets + {i}; } LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); } else{ LemmaHashEqualty(text_hash, text, i, old_text_hash, pattern); LemmaRabinKarp(text[i..i+|pattern|], pattern, text_hash, pattern_hash); } Lemma2Sides(text, pattern, i, offsets); //=> //=> } //=> } function RecursiveSumDown(str: string): int { if str == "" then 0 else str[|str|-1] as int +RecursiveSumDown(str[..|str|-1]) } function RecursiveSumUp(str: string): int { if str == "" then 0 else str[0] as int + RecursiveSumUp(str[1..]) } lemma {:verify true}LemmaRabinKarp(t_sub:string, pattern:string, text_hash:int, pattern_hash:int) requires text_hash != pattern_hash requires pattern_hash == RecursiveSumDown(pattern) requires text_hash == RecursiveSumDown(t_sub) ensures t_sub[..] != pattern[..] {} lemma Lemma2Sides(text: string, pattern: string, i: nat, offsets: set<nat>) requires 0 <= i <= |text| - |pattern| requires (text[i..i+|pattern|] == pattern ==> i in offsets) requires (text[i..i+|pattern|] == pattern <== i in offsets) ensures (text[i..i+|pattern|] == pattern <==> i in offsets) {} lemma LemmaHashEqualty(text_hash : int, text: string, i: nat, old_text_hash: int, pattern: string) requires 0 < i <= |text| - |pattern| requires text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int requires old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]); ensures text_hash == RecursiveSumDown(text[i..i+|pattern|]) { ghost var temp_val := old_text_hash + text[i - 1 + |pattern|] as int; //=> ghost var str := text[i - 1..]; LemmaAddingOneIndex(str, |pattern|, old_text_hash); //=> //=> PrependSumUp(text[i - 1..i + |pattern|]); EquivalentSumDefinitions(text[i - 1..i + |pattern|]); EquivalentSumDefinitions(text[i..i + |pattern|]); //=> //=> //=> //=> } lemma LemmaAddingOneIndex(str: string, i: nat, sum: int) requires 0 <= i < |str| && sum == RecursiveSumDown(str[..i]) ensures 0 <= i+1 <= |str| && sum + str[i] as int == RecursiveSumDown(str[..i+1]) { var str1 := str[..i+1]; calc { RecursiveSumDown(str[..i+1]); == // def. if str1 == [] then 0 else str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert str1 != []; } // simplification for a non-empty sequence str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]); == { assert |str1|-1 == i; } str1[i] as int + RecursiveSumDown(str1[..i]); == { assert str1[..i] == str[..i]; } str[i] as int + RecursiveSumDown(str[..i]); == // inv. str[i] as int + sum; == sum + str[i] as int; } } lemma PrependSumUp(str: string) requires str != "" ensures RecursiveSumUp(str) == str[0] as int + RecursiveSumUp(str[1..]) { // directly from the definition of RecursiveSumUp (for a non-emty sequence) } lemma EquivalentSumDefinitions(str: string) ensures RecursiveSumDown(str) == RecursiveSumUp(str) { if |str| == 0 { } else if |str| == 1 { } else { var first: char, mid: string, last:char := str[0], str[1..|str|-1], str[|str|-1]; calc { RecursiveSumDown(str); == { assert str != [] && str[|str|-1] == last && str[..|str|-1] == [first] + mid; } last as int + RecursiveSumDown([first] + mid); == // arithmetic RecursiveSumDown([first] + mid) + last as int; == { EquivalentSumDefinitions([first] + mid); } // induction hypothesis RecursiveSumUp([first] + mid) + last as int; == { assert [first] + mid != []; } first as int + RecursiveSumUp(mid) + last as int; == { EquivalentSumDefinitions(mid); } // induction hypothesis first as int + RecursiveSumDown(mid) + last as int; == first as int + RecursiveSumDown(mid + [last]); == { EquivalentSumDefinitions(mid + [last]); } // induction hypothesis first as int + RecursiveSumUp(mid + [last]); == { assert str != [] && str[0] == first && str[1..] == mid + [last]; } RecursiveSumUp(str); } } }
109
Dafny-Projects_tmp_tmph399drhy_p2_arraySplit.dfy
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; } }
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; } }
110
Dafny-VMC_tmp_tmpzgqv0i1u_src_Math_Exponential.dfy
module Exponential { ghost function {:axiom} Exp(x: real): real lemma {:axiom} FunctionalEquation(x: real, y: real) ensures Exp(x + y) == Exp(x) * Exp(y) lemma {:axiom} Increasing(x: real, y: real) requires x < y ensures Exp(x) < Exp(y) lemma {:axiom} EvalOne() ensures 2.718281828 <= Exp(1.0) <= 2.718281829 lemma Positive(x: real) ensures Exp(x) > 0.0 { assert Exp(x) >= 0.0 by { var sqrt := Exp(x / 2.0); calc { Exp(x); { FunctionalEquation(x / 2.0, x / 2.0); } sqrt * sqrt; >= 0.0; } } if Exp(x) == 0.0 { calc { 0.0; Exp(x); < { Increasing(x, x + 1.0); } Exp(x + 1.0); { FunctionalEquation(x, 1.0); } Exp(x) * Exp(1.0); == 0.0; } } } lemma EvalZero() ensures Exp(0.0) == 1.0 { var one := Exp(0.0); assert one > 0.0 by { Positive(0.0); } assert one * one == one by { FunctionalEquation(0.0, 0.0); } } }
module Exponential { ghost function {:axiom} Exp(x: real): real lemma {:axiom} FunctionalEquation(x: real, y: real) ensures Exp(x + y) == Exp(x) * Exp(y) lemma {:axiom} Increasing(x: real, y: real) requires x < y ensures Exp(x) < Exp(y) lemma {:axiom} EvalOne() ensures 2.718281828 <= Exp(1.0) <= 2.718281829 lemma Positive(x: real) ensures Exp(x) > 0.0 { var sqrt := Exp(x / 2.0); calc { Exp(x); { FunctionalEquation(x / 2.0, x / 2.0); } sqrt * sqrt; >= 0.0; } } if Exp(x) == 0.0 { calc { 0.0; Exp(x); < { Increasing(x, x + 1.0); } Exp(x + 1.0); { FunctionalEquation(x, 1.0); } Exp(x) * Exp(1.0); == 0.0; } } } lemma EvalZero() ensures Exp(0.0) == 1.0 { var one := Exp(0.0); Positive(0.0); } FunctionalEquation(0.0, 0.0); } } }
111
Dafny-VMC_tmp_tmpzgqv0i1u_src_Math_Helper.dfy
/******************************************************************************* * 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); } } }
/******************************************************************************* * 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); } } }
112
Dafny-demo_tmp_tmpkgr_dvdi_Dafny_BinarySearch.dfy
predicate sorted(a: array?<int>, l: int, u: int) reads a requires a != null { forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j] } method BinarySearch(a: array?<int>, key: int) returns (index: int) requires a != null && sorted(a,0,a.Length-1); ensures index >= 0 ==> index < a.Length && a[index] == key; ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key; { var low := 0; var high := a.Length; while (low < high) invariant 0 <= low <= high <= a.Length; invariant forall i :: 0 <= i < a.Length && !(low <= i < high) ==> a[i] != key; { var mid := (low + high) / 2; if (a[mid] < key) { low := mid + 1; } else if (key < a[mid]) { high := mid; } else { return mid; } } return -1; }
predicate sorted(a: array?<int>, l: int, u: int) reads a requires a != null { forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j] } method BinarySearch(a: array?<int>, key: int) returns (index: int) requires a != null && sorted(a,0,a.Length-1); ensures index >= 0 ==> index < a.Length && a[index] == key; ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key; { var low := 0; var high := a.Length; while (low < high) 0 <= i < a.Length && !(low <= i < high) ==> a[i] != key; { var mid := (low + high) / 2; if (a[mid] < key) { low := mid + 1; } else if (key < a[mid]) { high := mid; } else { return mid; } } return -1; }
113
Dafny-experiences_tmp_tmp150sm9qy_dafny_started_tutorial_dafny_tutorial_array.dfy
method FindMax(a: array<int>) returns (i: int) // Annotate this method with pre- and postconditions // that ensure it behaves as described. requires a.Length > 0 ensures 0<= i < a.Length ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i] { // Fill in the body that calculates the INDEX of the maximum. i := 0; var index := 1; while index < a.Length invariant 0 < index <= a.Length invariant 0 <= i < index invariant forall k :: 0 <= k < index ==> a[k] <= a[i] { if a[index] > a[i] {i:= index;} index := index + 1; } }
method FindMax(a: array<int>) returns (i: int) // Annotate this method with pre- and postconditions // that ensure it behaves as described. requires a.Length > 0 ensures 0<= i < a.Length ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i] { // Fill in the body that calculates the INDEX of the maximum. i := 0; var index := 1; while index < a.Length { if a[index] > a[i] {i:= index;} index := index + 1; } }
114
Dafny-programs_tmp_tmpnso9eu7u_Algorithms + sorting_bubble-sort.dfy
/* 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 */
/* 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 */
115
DafnyExercises_tmp_tmpd6qyevja_Part1_Q1.dfy
method addArrays(a : array<int>, b : array<int>) returns (c : array<int>) requires a.Length == b.Length ensures b.Length == c.Length ensures forall i:int :: 0 <= i <c.Length ==> c[i] == a[i] + b[i] { c := new int[a.Length]; var j := 0; while (j < a.Length) invariant 0 <= j <= c.Length invariant forall i :: (0 <= i < j) ==> c[i] == a[i] + b[i]; { c[j] := a[j] + b[j]; j := j + 1; } }
method addArrays(a : array<int>, b : array<int>) returns (c : array<int>) requires a.Length == b.Length ensures b.Length == c.Length ensures forall i:int :: 0 <= i <c.Length ==> c[i] == a[i] + b[i] { c := new int[a.Length]; var j := 0; while (j < a.Length) { c[j] := a[j] + b[j]; j := j + 1; } }
116
DafnyExercises_tmp_tmpd6qyevja_QuickExercises_testing2.dfy
// predicate recSorted(s : string) decreases s // { // if (|s| <=1) then true else if(s[0] > s[1]) then false else recSorted(s[1..]) // } // predicate forallSorted (s : string) // { // forall x,y::0<x<y<|s|==>s[x]<s[y] // } // lemma forallEQrec(a:string) // ensures forallSorted(a) == recSorted(a) { // } // // method Main() { // // print "\nYou must save your answer for later use!\n"; // // assert "acbed"[1] > "acbed"[2]; // // assert !forallSorted("acbed"); // // assert forallSorted("abcde"); // // } // /*omitted*/ /* verify one of ensures r == forallSorted(a) OR ensures r == recSorted(a) Only one might work */ // method whileSorted(a:string) returns (r : bool) // ensures r == forallSorted(a) // ONEOF // //ensures r == recSorted(a) // ONEOF // { // var i := 1; // r := true; // if |a| <=1 { // return true; // } // while i <|a| // invariant 0 < i <= |a| // invariant r == forallSorted(a[..i]) // decreases |a| -i { // if a[i-1] > a[i] { // r:= false; // } // i := i+1; // } // } // lemma SortedSumForall(a:string,b:string) // requires forallSorted(a) // requires forallSorted(b) // ensures forallSorted(a + b) // requires (|a| >0 && |b| >0 ) ==> a[|a|-1] <= b[0] // { // } // /*omitted*/ // // Prove using forallSorted not recursivly using SortedSumRec // lemma SortedSumRec(a:string,b:string) // requires recSorted(a) // requires recSorted(b) // requires |a| > 0 && |b| > 0 // requires a[|a|-1] <= b[0] // ensures recSorted(a + b) // { // forallEQrec(a); // forallEQrec(b); // forallEQrec(a+b); // } // predicate recSorted(s : string) decreases s // /*omitted*/ // // Prove using Induction not using forallEQrec // lemma SortedSumInduction(a:string,b:string) // requires recSorted(a) // requires recSorted(b) // requires |a| > 0 && |b| > 0 // requires a[|a|-1] <= b[0] // ensures recSorted(a + b) // { // if |a| < 2 { // } else { // SortedSumInduction(a[1..],b); // assert recSorted(a[1..] +b); // assert [a[0]] + a[1..] == a; // assert recSorted([a[0]] + a[1..]); // assert [a[0]] + (a[1..] + b) == ([a[0]] + a[1..]) + b; // assert recSorted(a+b); // } // } // lemma VowelsLemma(s : string, t : string) // ensures vowels(s + t) == vowels(s) + vowels(t) // //verify this lemma - https://youtu.be/LFLD48go9os // { // if |s| > 0 { // assert [s[0]] + s[1..] == s; // assert [s[0]] + (s[1..] + t) == ([s[0]] + s[1..]) + t; // } else if |t| > 0 { // assert [t[0]] + t[1..] == t; // assert (s + [t[0]]) + t[1..] == s +([t[0]] + t[1..]); // } // } //so far straightwawrd // function vowels(s : string) : (r : nat) // { // if (|s| == 0) then 0 // else // (if (s[0] in "aeiou") then 1 else 0) // + vowels(s[1..]) // } // //see, this one is soooo EASY!!! // function vowelsF(s : string) : nat { // var m := multiset(s); // m['a'] + m['e'] + m['i'] + m['o'] + m['u'] // } // lemma VowelsLemmaF(s : string, t : string) // ensures vowelsF(s + t) == vowelsF(s) + vowelsF(t) // {} // // method Main() { // // print "have you verified one of: \n ensures r == forallSorted(a) or \n ensures r == recSorted(a)\n"; // // print "\nYou must save your answer for later use!\n"; // // assert "acbed"[1] > "acbed"[2]; // // var nb := whileSorted("acbed"); // // assert !nb; // // var b := whileSorted("abcde"); // // assert b; // // } // class KlingonCalendar { // var dayOfWeek : int // const DAYS := ["dishonour", "destruction", "defeat", "death", "victory"] //-3, -2, -1, 0, 1 // var weekOfMonth : int // const WEEKS := [ "polishing spaceships", "carousing", "battle"] // -1, 0, 1 // var monthOfYear : int // const MONTHS := ["peace", "pestilence", "famine", "flood", "covid", "war", "slaughter"] //-5, -4 -3, -3, -1, 0, 1 // var year : nat // //Define a "Valid()" predicate as a class invariant so that // //the rest of the class methods don't have to repeat everything! // predicate Valid() // reads this // { // (-3<=dayOfWeek <= 1) && (-1<=weekOfMonth<=1) && (-5<monthOfYear<=1) // } // method printDate() // requires Valid(); // { // print "The day of "; // print DAYS[dayOfWeek+3]; // print " in the week of "; // print WEEKS[weekOfMonth+1]; // print " in the month of "; // print MONTHS[monthOfYear+5]; // print " in the year ", year + 2300, "\n"; // } // } // lemma VowelsLemma(s : string, t : string) // ensures vowels(s + t) == vowels(s) + vowels(t) // //verify this lemma - https://youtu.be/LFLD48go9os // { // } // //so far straightwawrd // function vowels(s : string) : (r : nat) // { // if (|s| == 0) then 0 // else // (if (s[0] in "aeiou") then 1 else 0) // + vowels(s[1..]) // } // //see, this one is soooo EASY!!! // function vowelsF(s : string) : nat { // var m := multiset(s); // m['a'] + m['e'] + m['i'] + m['o'] + m['u'] // } // lemma VowelsLemmaF(s : string, t : string) // ensures vowelsF(s + t) == vowelsF(s) + vowelsF(t) // {} // class Stack { // const values : array<int>; // const capacity : nat; // var size : nat; // constructor(capacity_ : nat) // /*omitted*/ // method push(i : int) // modifies this, values // requires size <values.Length // requires size < capacity // ensures size <= capacity // ensures values[old(size)] == i // ensures size == old(size) + 1 // ensures size > 0 // ensures values[size-1] == i // ensures size == old(size) +1 // ensures old(size) < values.Length // ensures old(size) >= 0 // ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i]{ // values[size] :=i; // size:= size + 1; // } // method pop() returns (r : int) // modifies this // requires 0 <size<values.Length // requires size <= capacity // ensures size < capacity // ensures size >= 0 // ensures size == old(size) -1 // ensures r == values[old(size-1)] // ensures r == values[size] // { // r := values[size-1]; // size := size -1; // } // } // method VerifyStack(s : Stack, i : int, j : int) // modifies s, s.values // requires 0 <= s.size < (s.values.Length - 2) // requires s.values.Length == s.capacity // requires s.size == 0 // { // s.push(i); // s.push(j); // var v := s.pop(); // assert v == j; // v := s.pop(); // assert v == i; // } // datatype StackModel = Empty | Push(value : int, prev : StackModel) // class Stack { // const values : array<int>; // const capacity : nat; // var size : nat; // function method toStackModel() : StackModel // requires 0 <= size <= capacity // requires values.Length == capacity // reads this, values // {toStackModelAux(size)} // function method toStackModelAux(i : nat) : StackModel // //requires 0 <= i <= size <= capacity // requires 0 <= i <= capacity // requires values.Length == capacity // reads values // decreases i // { // if (i == 0) then Empty // else Push(values[i-1],toStackModelAux(i-1)) // } // //Here's where you need to re-use your code // //Copy in your existing code for these methods // // // predicate Valid() // reads this // { // size <= values.Length && values.Length == capacity // } // constructor(capacity_ : nat) // ensures capacity == capacity_ // ensures Valid() // // ensures values.Length == capacity_ // // ensures values.Length == capacity // ensures size ==0 // ensures forall i:nat::i<values.Length ==>values[i] ==0{ // capacity := capacity_; // values := new int[capacity_](x=>0); // size := 0; // } // method push(i : int) // modifies this, values // requires Valid() // requires size <values.Length // requires size < capacity // requires 0 <= size <= capacity // requires values.Length == capacity // ensures size <= capacity // ensures values[old(size)] == i // ensures size == old(size) + 1 // ensures size > 0 // ensures values[size-1] == i // ensures size == old(size) +1 // ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i] // ensures forall i :: 0 <= i <= old(size) ==> old(this.toStackModelAux(i)) == this.toStackModelAux(i) // ensures this.toStackModel().value == i // { // values[size] :=i; // size:= size + 1; // } // method pop() returns (r : int) // modifies this // requires 0 <size<values.Length // requires size <= capacity // ensures size < capacity // ensures size >= 0 // ensures size == old(size) -1 // ensures r == values[old(size-1)] // ensures r == values[size] // { // r := values[size-1]; // size := size -1; // } // function method top() : (r : int) // reads values // reads this // requires values.Length > 0 // requires size > 0 // requires size <= values.Length // ensures r == values[size-1]{ // values[size-1] // } // } // method StackModelOK(s : Stack, i : int, j : int) // requires s.values.Length == s.capacity // modifies s, s.values // requires s.size == 0 // requires s.capacity > 2 // { // var sSM := s.toStackModel(); // s.push(i); // assert s.toStackModel() == Push(i,sSM); // var v := s.pop(); // assert v == i; // assert s.toStackModel() == sSM; // s.push(i); // assert s.toStackModel() == Push(i,sSM); // assert (Push(i,sSM).prev) == sSM; // s.push(j); // assert s.toStackModel() == Push(j,Push(i,sSM)); // v := s.top(); // assert v == j; // v := s.pop(); // assert v == j; // assert s.toStackModel() == Push(i,sSM); // v := s.pop(); // assert v == i; // var t := new Stack(10); // assert t.toStackModel() == Empty; // } // datatype StackModel = Empty | Push(value : int, prev : StackModel) // class Stack { // var values : array<int> // var capacity : nat // var size : nat // ghost const Repr : set<object> //Last Stack ("bis") question (for now!!!) - https://youtu.be/Goj8QCOkq-w // //Chapter 16 goes on to talk about how to define a Repr field //to outline the representation of the abstraction you're modelling //so you don't have to name all the objects involved in modifies //clauses, just refer to the whole Repr. // //Copy and paste your code for the final time, then edit your //constructor and Valid() class invariant so that the hidden //code in here should work. Define just these two methods: // // predicate Valid() // reads Repr // { // this in Repr && values in Repr && size <= values.Length && values.Length == capacity // } // constructor(capacity_ : nat) // ensures capacity == capacity_ // ensures Valid() // ensures values.Length == capacity_ // ensures values.Length == capacity // ensures size ==0 // ensures forall i:nat::i<values.Length ==>values[i] ==0{ // capacity := capacity_; // values := new int[capacity_](x=>0); // size := 0; // Repr := {this,values}; // } // function method toStackModel() : StackModel // reads Repr // requires Valid() // /*omitted*/ // function method toStackModelAux(i : nat) : StackModel // reads Repr // requires Valid() // /*omitted*/ // method push(i : int) // requires Valid() // ensures Valid() // modifies Repr // ensures capacity == old(capacity) // /*omitted*/ // method pop() returns (r : int) // requires Valid() // modifies this`size; // ensures Valid(); // /*omitted*/ // function method top() : (r : int) // requires Valid() // reads Repr // ensures Valid(); // /*omitted*/ // } // method StackOK(s : Stack, i : int, j : int) // requires s.Valid() // requires 0 <= s.size < (s.capacity - 2) // requires s.values.Length == s.capacity // requires s.size == 0 // requires s.capacity > 2 // modifies s.Repr // { // var sSM := s.toStackModel(); // assert s.size == 0; // assert sSM.Empty?; // s.push(i); // assert s.toStackModel() == Push(i,sSM); // var v := s.pop(); // assert v == i; // assert s.toStackModel() == sSM; // s.push(i); // assert s.toStackModel() == Push(i,sSM); // assert Push(i,sSM).prev == sSM; // s.push(j); // assert s.toStackModel() == Push(j,Push(i,sSM)); // v := s.top(); // assert v == j; // v := s.pop(); // assert v == j; // assert s.toStackModel() == Push(i,sSM); // v := s.pop(); // assert v == i; // }
// predicate recSorted(s : string) decreases s // { // if (|s| <=1) then true else if(s[0] > s[1]) then false else recSorted(s[1..]) // } // predicate forallSorted (s : string) // { // forall x,y::0<x<y<|s|==>s[x]<s[y] // } // lemma forallEQrec(a:string) // ensures forallSorted(a) == recSorted(a) { // } // // method Main() { // // print "\nYou must save your answer for later use!\n"; // // assert "acbed"[1] > "acbed"[2]; // // assert !forallSorted("acbed"); // // assert forallSorted("abcde"); // // } // /*omitted*/ /* verify one of ensures r == forallSorted(a) OR ensures r == recSorted(a) Only one might work */ // method whileSorted(a:string) returns (r : bool) // ensures r == forallSorted(a) // ONEOF // //ensures r == recSorted(a) // ONEOF // { // var i := 1; // r := true; // if |a| <=1 { // return true; // } // while i <|a| // invariant 0 < i <= |a| // invariant r == forallSorted(a[..i]) // decreases |a| -i { // if a[i-1] > a[i] { // r:= false; // } // i := i+1; // } // } // lemma SortedSumForall(a:string,b:string) // requires forallSorted(a) // requires forallSorted(b) // ensures forallSorted(a + b) // requires (|a| >0 && |b| >0 ) ==> a[|a|-1] <= b[0] // { // } // /*omitted*/ // // Prove using forallSorted not recursivly using SortedSumRec // lemma SortedSumRec(a:string,b:string) // requires recSorted(a) // requires recSorted(b) // requires |a| > 0 && |b| > 0 // requires a[|a|-1] <= b[0] // ensures recSorted(a + b) // { // forallEQrec(a); // forallEQrec(b); // forallEQrec(a+b); // } // predicate recSorted(s : string) decreases s // /*omitted*/ // // Prove using Induction not using forallEQrec // lemma SortedSumInduction(a:string,b:string) // requires recSorted(a) // requires recSorted(b) // requires |a| > 0 && |b| > 0 // requires a[|a|-1] <= b[0] // ensures recSorted(a + b) // { // if |a| < 2 { // } else { // SortedSumInduction(a[1..],b); // assert recSorted(a[1..] +b); // assert [a[0]] + a[1..] == a; // assert recSorted([a[0]] + a[1..]); // assert [a[0]] + (a[1..] + b) == ([a[0]] + a[1..]) + b; // assert recSorted(a+b); // } // } // lemma VowelsLemma(s : string, t : string) // ensures vowels(s + t) == vowels(s) + vowels(t) // //verify this lemma - https://youtu.be/LFLD48go9os // { // if |s| > 0 { // assert [s[0]] + s[1..] == s; // assert [s[0]] + (s[1..] + t) == ([s[0]] + s[1..]) + t; // } else if |t| > 0 { // assert [t[0]] + t[1..] == t; // assert (s + [t[0]]) + t[1..] == s +([t[0]] + t[1..]); // } // } //so far straightwawrd // function vowels(s : string) : (r : nat) // { // if (|s| == 0) then 0 // else // (if (s[0] in "aeiou") then 1 else 0) // + vowels(s[1..]) // } // //see, this one is soooo EASY!!! // function vowelsF(s : string) : nat { // var m := multiset(s); // m['a'] + m['e'] + m['i'] + m['o'] + m['u'] // } // lemma VowelsLemmaF(s : string, t : string) // ensures vowelsF(s + t) == vowelsF(s) + vowelsF(t) // {} // // method Main() { // // print "have you verified one of: \n ensures r == forallSorted(a) or \n ensures r == recSorted(a)\n"; // // print "\nYou must save your answer for later use!\n"; // // assert "acbed"[1] > "acbed"[2]; // // var nb := whileSorted("acbed"); // // assert !nb; // // var b := whileSorted("abcde"); // // assert b; // // } // class KlingonCalendar { // var dayOfWeek : int // const DAYS := ["dishonour", "destruction", "defeat", "death", "victory"] //-3, -2, -1, 0, 1 // var weekOfMonth : int // const WEEKS := [ "polishing spaceships", "carousing", "battle"] // -1, 0, 1 // var monthOfYear : int // const MONTHS := ["peace", "pestilence", "famine", "flood", "covid", "war", "slaughter"] //-5, -4 -3, -3, -1, 0, 1 // var year : nat // //Define a "Valid()" predicate as a class invariant so that // //the rest of the class methods don't have to repeat everything! // predicate Valid() // reads this // { // (-3<=dayOfWeek <= 1) && (-1<=weekOfMonth<=1) && (-5<monthOfYear<=1) // } // method printDate() // requires Valid(); // { // print "The day of "; // print DAYS[dayOfWeek+3]; // print " in the week of "; // print WEEKS[weekOfMonth+1]; // print " in the month of "; // print MONTHS[monthOfYear+5]; // print " in the year ", year + 2300, "\n"; // } // } // lemma VowelsLemma(s : string, t : string) // ensures vowels(s + t) == vowels(s) + vowels(t) // //verify this lemma - https://youtu.be/LFLD48go9os // { // } // //so far straightwawrd // function vowels(s : string) : (r : nat) // { // if (|s| == 0) then 0 // else // (if (s[0] in "aeiou") then 1 else 0) // + vowels(s[1..]) // } // //see, this one is soooo EASY!!! // function vowelsF(s : string) : nat { // var m := multiset(s); // m['a'] + m['e'] + m['i'] + m['o'] + m['u'] // } // lemma VowelsLemmaF(s : string, t : string) // ensures vowelsF(s + t) == vowelsF(s) + vowelsF(t) // {} // class Stack { // const values : array<int>; // const capacity : nat; // var size : nat; // constructor(capacity_ : nat) // /*omitted*/ // method push(i : int) // modifies this, values // requires size <values.Length // requires size < capacity // ensures size <= capacity // ensures values[old(size)] == i // ensures size == old(size) + 1 // ensures size > 0 // ensures values[size-1] == i // ensures size == old(size) +1 // ensures old(size) < values.Length // ensures old(size) >= 0 // ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i]{ // values[size] :=i; // size:= size + 1; // } // method pop() returns (r : int) // modifies this // requires 0 <size<values.Length // requires size <= capacity // ensures size < capacity // ensures size >= 0 // ensures size == old(size) -1 // ensures r == values[old(size-1)] // ensures r == values[size] // { // r := values[size-1]; // size := size -1; // } // } // method VerifyStack(s : Stack, i : int, j : int) // modifies s, s.values // requires 0 <= s.size < (s.values.Length - 2) // requires s.values.Length == s.capacity // requires s.size == 0 // { // s.push(i); // s.push(j); // var v := s.pop(); // assert v == j; // v := s.pop(); // assert v == i; // } // datatype StackModel = Empty | Push(value : int, prev : StackModel) // class Stack { // const values : array<int>; // const capacity : nat; // var size : nat; // function method toStackModel() : StackModel // requires 0 <= size <= capacity // requires values.Length == capacity // reads this, values // {toStackModelAux(size)} // function method toStackModelAux(i : nat) : StackModel // //requires 0 <= i <= size <= capacity // requires 0 <= i <= capacity // requires values.Length == capacity // reads values // decreases i // { // if (i == 0) then Empty // else Push(values[i-1],toStackModelAux(i-1)) // } // //Here's where you need to re-use your code // //Copy in your existing code for these methods // // // predicate Valid() // reads this // { // size <= values.Length && values.Length == capacity // } // constructor(capacity_ : nat) // ensures capacity == capacity_ // ensures Valid() // // ensures values.Length == capacity_ // // ensures values.Length == capacity // ensures size ==0 // ensures forall i:nat::i<values.Length ==>values[i] ==0{ // capacity := capacity_; // values := new int[capacity_](x=>0); // size := 0; // } // method push(i : int) // modifies this, values // requires Valid() // requires size <values.Length // requires size < capacity // requires 0 <= size <= capacity // requires values.Length == capacity // ensures size <= capacity // ensures values[old(size)] == i // ensures size == old(size) + 1 // ensures size > 0 // ensures values[size-1] == i // ensures size == old(size) +1 // ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i] // ensures forall i :: 0 <= i <= old(size) ==> old(this.toStackModelAux(i)) == this.toStackModelAux(i) // ensures this.toStackModel().value == i // { // values[size] :=i; // size:= size + 1; // } // method pop() returns (r : int) // modifies this // requires 0 <size<values.Length // requires size <= capacity // ensures size < capacity // ensures size >= 0 // ensures size == old(size) -1 // ensures r == values[old(size-1)] // ensures r == values[size] // { // r := values[size-1]; // size := size -1; // } // function method top() : (r : int) // reads values // reads this // requires values.Length > 0 // requires size > 0 // requires size <= values.Length // ensures r == values[size-1]{ // values[size-1] // } // } // method StackModelOK(s : Stack, i : int, j : int) // requires s.values.Length == s.capacity // modifies s, s.values // requires s.size == 0 // requires s.capacity > 2 // { // var sSM := s.toStackModel(); // s.push(i); // assert s.toStackModel() == Push(i,sSM); // var v := s.pop(); // assert v == i; // assert s.toStackModel() == sSM; // s.push(i); // assert s.toStackModel() == Push(i,sSM); // assert (Push(i,sSM).prev) == sSM; // s.push(j); // assert s.toStackModel() == Push(j,Push(i,sSM)); // v := s.top(); // assert v == j; // v := s.pop(); // assert v == j; // assert s.toStackModel() == Push(i,sSM); // v := s.pop(); // assert v == i; // var t := new Stack(10); // assert t.toStackModel() == Empty; // } // datatype StackModel = Empty | Push(value : int, prev : StackModel) // class Stack { // var values : array<int> // var capacity : nat // var size : nat // ghost const Repr : set<object> //Last Stack ("bis") question (for now!!!) - https://youtu.be/Goj8QCOkq-w // //Chapter 16 goes on to talk about how to define a Repr field //to outline the representation of the abstraction you're modelling //so you don't have to name all the objects involved in modifies //clauses, just refer to the whole Repr. // //Copy and paste your code for the final time, then edit your //constructor and Valid() class invariant so that the hidden //code in here should work. Define just these two methods: // // predicate Valid() // reads Repr // { // this in Repr && values in Repr && size <= values.Length && values.Length == capacity // } // constructor(capacity_ : nat) // ensures capacity == capacity_ // ensures Valid() // ensures values.Length == capacity_ // ensures values.Length == capacity // ensures size ==0 // ensures forall i:nat::i<values.Length ==>values[i] ==0{ // capacity := capacity_; // values := new int[capacity_](x=>0); // size := 0; // Repr := {this,values}; // } // function method toStackModel() : StackModel // reads Repr // requires Valid() // /*omitted*/ // function method toStackModelAux(i : nat) : StackModel // reads Repr // requires Valid() // /*omitted*/ // method push(i : int) // requires Valid() // ensures Valid() // modifies Repr // ensures capacity == old(capacity) // /*omitted*/ // method pop() returns (r : int) // requires Valid() // modifies this`size; // ensures Valid(); // /*omitted*/ // function method top() : (r : int) // requires Valid() // reads Repr // ensures Valid(); // /*omitted*/ // } // method StackOK(s : Stack, i : int, j : int) // requires s.Valid() // requires 0 <= s.size < (s.capacity - 2) // requires s.values.Length == s.capacity // requires s.size == 0 // requires s.capacity > 2 // modifies s.Repr // { // var sSM := s.toStackModel(); // assert s.size == 0; // assert sSM.Empty?; // s.push(i); // assert s.toStackModel() == Push(i,sSM); // var v := s.pop(); // assert v == i; // assert s.toStackModel() == sSM; // s.push(i); // assert s.toStackModel() == Push(i,sSM); // assert Push(i,sSM).prev == sSM; // s.push(j); // assert s.toStackModel() == Push(j,Push(i,sSM)); // v := s.top(); // assert v == j; // v := s.pop(); // assert v == j; // assert s.toStackModel() == Push(i,sSM); // v := s.pop(); // assert v == i; // }
117
DafnyPrograms_tmp_tmp74_f9k_c_automaton.dfy
/** Consider cellular automata: a row of cells is repeatedly updated according to a rule. In this exercise I dabbled with, each cell has the value either false or true. Each cell's next state depends only on the immediate neighbours, in the case where the cell is at the edges of the row, the inexistent neighbours are replaced by "false". The automaton table will contain the initial row, plus a row for each number of steps. */ class Automaton { /** This method computes the automaton. Provide the initial row: init, the rule and the desired number of steps */ method ExecuteAutomaton(init: seq<bool>, rule: (bool, bool, bool) -> bool, steps: nat) returns (table: seq<seq<bool>>) // we need the initial row to have the length bigger or equal to two requires |init| >= 2 // after computation the automaton is made of the initial row plus a row for each of the steps ensures |table| == 1 + steps // the automaton must have the initial row at the top ensures table[0] == init; // all rows in the automaton must be the same length ensures forall i | 0 <= i < |table| :: |table[i]| == |init| // all the middle row elements (with existing neighbours) after a step, will be equal to the rule applied on the element in the previous state // and its neigbours ensures forall i | 0 <= i < |table| - 1 :: forall j | 1 <= j <= |table[i]| - 2 :: table[i + 1][j] == rule(table[i][j - 1], table[i][j], table[i][j + 1]) // the corner row elements (with non-existing neighbours) after a step, will be equal to the rule applied on the element in the previous state, // its neighbour and false ensures forall i | 0 <= i < |table| - 1 :: table[i + 1][0] == rule(false, table[i][0], table[i][1]) && table[i + 1][|table[i]| - 1] == rule(table[i][|table[i]| - 2], table[i][|table[i]| - 1], false) { // the table containing the automaton var result : seq<seq<bool>> := [init]; // the current row var currentSeq := init; var index := 0; while index < steps invariant 0 <= index <= steps // the length of the table will be the index + 1, since it starts with an element and at every loop iteration we add a row to it invariant |result| == index + 1 // the first element of the table is the init row invariant result[0] == init // the lenght of the rows in the table are equal invariant |currentSeq| == |init| invariant forall i | 0 <= i < |result| :: |result[i]| == |init| // Dafny needs mentioning that that the currentSeq is equal to the element at position index in the table invariant currentSeq == result[index] // invariant for the first ensures condition obtained by replacing constant with variable invariant forall i | 0 <= i < |result| - 1 :: forall j | 1 <= j <= |result[i]| - 2 :: result[i + 1][j] == rule(result[i][j - 1], result[i][j], result[i][j + 1]) // invariant for the second ensures condition obtained by replacing constant with variable invariant forall i | 0 <= i < |result| - 1 :: result[i + 1][0] == rule(false, result[i][0], result[i][1]) && result[i + 1][|result[i]| - 1] == rule(result[i][|result[i]| - 2], result[i][|result[i]| - 1], false) // the decreases clause to prove termination of this loop decreases steps - index { var index2 := 1; // the next row to be computed var nextSeq := []; nextSeq := nextSeq + [rule(false, currentSeq[0], currentSeq[1])]; while index2 < |currentSeq| - 1 invariant |currentSeq| == |init| invariant 0 <= index2 <= |currentSeq| - 1 invariant |nextSeq| == index2 // even though its trivial, Dafny needs mentioning that the below invariant holds at every iteration of the loop, // since nextSeq[0] was initialized before entering the loop invariant nextSeq[0] == rule(false, currentSeq[0], currentSeq[1]) // all elements smaller than index2 are already present in the new row with the value calculated by the rule, // the element at index2 is still to be computed inside the while loop, thus when entering the loop // the rule value does not yet hold for it invariant forall i | 1 <= i < index2 :: nextSeq[i] == rule(currentSeq[i - 1], currentSeq[i], currentSeq[i + 1]) decreases |currentSeq| - index2 { nextSeq := nextSeq + [rule(currentSeq[index2 - 1], currentSeq[index2], currentSeq[index2 + 1])]; index2 := index2 + 1; } nextSeq := nextSeq + [rule(currentSeq[|currentSeq| - 2], currentSeq[|currentSeq| - 1], false)]; currentSeq := nextSeq; result := result + [nextSeq]; index := index + 1; } return result; } // example rule function TheRule(a: bool, b: bool, c: bool) : bool { a || b || c } // example rule 2 function TheRule2(a: bool, b: bool, c: bool) : bool { a && b && c } method testMethod() { // the initial row var init := [false, false, true, false, false]; // calculate automaton steps with var result := ExecuteAutomaton(init, TheRule, 3); // the intial row plus the three steps of the automaton are showed bellow assert(result[0] == [false, false, true, false, false]); // the initial state of the automaton assert(result[1] == [false, true, true, true, false]); // after the first step assert(result[2] == [true, true, true, true, true]); // after the second step assert(result[3] == [true, true, true, true, true]); // after the third step, remains the same from now on var result2 := ExecuteAutomaton(init, TheRule2, 2); // the intial row plus the two steps of the automaton are showed bellow assert(result2[0] == [false, false, true, false, false]); // the initial state of the automaton assert(result2[1] == [false, false, false, false, false]); // after the first step assert(result2[2] == [false, false, false, false, false]); // after the second step, remains the same from now on } }
/** Consider cellular automata: a row of cells is repeatedly updated according to a rule. In this exercise I dabbled with, each cell has the value either false or true. Each cell's next state depends only on the immediate neighbours, in the case where the cell is at the edges of the row, the inexistent neighbours are replaced by "false". The automaton table will contain the initial row, plus a row for each number of steps. */ class Automaton { /** This method computes the automaton. Provide the initial row: init, the rule and the desired number of steps */ method ExecuteAutomaton(init: seq<bool>, rule: (bool, bool, bool) -> bool, steps: nat) returns (table: seq<seq<bool>>) // we need the initial row to have the length bigger or equal to two requires |init| >= 2 // after computation the automaton is made of the initial row plus a row for each of the steps ensures |table| == 1 + steps // the automaton must have the initial row at the top ensures table[0] == init; // all rows in the automaton must be the same length ensures forall i | 0 <= i < |table| :: |table[i]| == |init| // all the middle row elements (with existing neighbours) after a step, will be equal to the rule applied on the element in the previous state // and its neigbours ensures forall i | 0 <= i < |table| - 1 :: forall j | 1 <= j <= |table[i]| - 2 :: table[i + 1][j] == rule(table[i][j - 1], table[i][j], table[i][j + 1]) // the corner row elements (with non-existing neighbours) after a step, will be equal to the rule applied on the element in the previous state, // its neighbour and false ensures forall i | 0 <= i < |table| - 1 :: table[i + 1][0] == rule(false, table[i][0], table[i][1]) && table[i + 1][|table[i]| - 1] == rule(table[i][|table[i]| - 2], table[i][|table[i]| - 1], false) { // the table containing the automaton var result : seq<seq<bool>> := [init]; // the current row var currentSeq := init; var index := 0; while index < steps // the length of the table will be the index + 1, since it starts with an element and at every loop iteration we add a row to it // the first element of the table is the init row // the lenght of the rows in the table are equal // Dafny needs mentioning that that the currentSeq is equal to the element at position index in the table // invariant for the first ensures condition obtained by replacing constant with variable forall j | 1 <= j <= |result[i]| - 2 :: result[i + 1][j] == rule(result[i][j - 1], result[i][j], result[i][j + 1]) // invariant for the second ensures condition obtained by replacing constant with variable result[i + 1][0] == rule(false, result[i][0], result[i][1]) && result[i + 1][|result[i]| - 1] == rule(result[i][|result[i]| - 2], result[i][|result[i]| - 1], false) // the decreases clause to prove termination of this loop { var index2 := 1; // the next row to be computed var nextSeq := []; nextSeq := nextSeq + [rule(false, currentSeq[0], currentSeq[1])]; while index2 < |currentSeq| - 1 // even though its trivial, Dafny needs mentioning that the below invariant holds at every iteration of the loop, // since nextSeq[0] was initialized before entering the loop // all elements smaller than index2 are already present in the new row with the value calculated by the rule, // the element at index2 is still to be computed inside the while loop, thus when entering the loop // the rule value does not yet hold for it { nextSeq := nextSeq + [rule(currentSeq[index2 - 1], currentSeq[index2], currentSeq[index2 + 1])]; index2 := index2 + 1; } nextSeq := nextSeq + [rule(currentSeq[|currentSeq| - 2], currentSeq[|currentSeq| - 1], false)]; currentSeq := nextSeq; result := result + [nextSeq]; index := index + 1; } return result; } // example rule function TheRule(a: bool, b: bool, c: bool) : bool { a || b || c } // example rule 2 function TheRule2(a: bool, b: bool, c: bool) : bool { a && b && c } method testMethod() { // the initial row var init := [false, false, true, false, false]; // calculate automaton steps with var result := ExecuteAutomaton(init, TheRule, 3); // the intial row plus the three steps of the automaton are showed bellow var result2 := ExecuteAutomaton(init, TheRule2, 2); // the intial row plus the two steps of the automaton are showed bellow } }
118
DafnyPrograms_tmp_tmp74_f9k_c_invertarray.dfy
/** Inverts an array of ints. */ method InvertArray(a: array<int>) modifies a ensures forall i | 0 <= i < a.Length :: a[i] == old(a[a.Length-1-i]) { var index := 0; while index < a.Length / 2 invariant 0 <= index <= a.Length / 2 // the elements i before position index are already switched with the old value of position a.Length - 1 - i invariant forall i | 0 <= i < index :: a[i] == old(a[a.Length - 1 - i]) // the elements of form a.Length - 1 - i after position a.Length - 1 - index are already switched with the old value of position i invariant forall i | 0 <= i < index :: a[a.Length - 1 - i] == old(a[i]) // the elements between index and a.Length - index are unchanged : the middle of the array invariant forall i | index <= i < a.Length - index :: a[i] == old(a[i]) { a[index], a[a.Length - 1 - index] := a[a.Length - 1 - index], a[index]; index := index + 1; } }
/** Inverts an array of ints. */ method InvertArray(a: array<int>) modifies a ensures forall i | 0 <= i < a.Length :: a[i] == old(a[a.Length-1-i]) { var index := 0; while index < a.Length / 2 // the elements i before position index are already switched with the old value of position a.Length - 1 - i // the elements of form a.Length - 1 - i after position a.Length - 1 - index are already switched with the old value of position i // the elements between index and a.Length - index are unchanged : the middle of the array { a[index], a[a.Length - 1 - index] := a[a.Length - 1 - index], a[index]; index := index + 1; } }
119
DafnyPrograms_tmp_tmp74_f9k_c_map-multiset-implementation.dfy
/** 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); } }
/** 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); } }
120
DafnyPrograms_tmp_tmp74_f9k_c_prime-database.dfy
//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; }
//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); }
121
DafnyProjects_tmp_tmp2acw_s4s_CombNK.dfy
/* * 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; }
/* * 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() { }
122
DafnyProjects_tmp_tmp2acw_s4s_Graph.dfy
// Simple directed graph with vertices of any type T. class {:autocontracts} Graph<T(==)> { var V: set<T>; // vertex-set var E: set<(T, T)>; // edge-set // Class invariant. ghost predicate Valid() { // edges must refer to vertices that belong to the vertex-set // and self-loops (edges connecting a vertex to itself) are not allowed forall e :: e in E ==> e.0 in V && e.1 in V && e.0 != e.1 } // Creates an empty graph. constructor () ensures V == {} && E == {} { V:= {}; E := {}; } // Adds a new vertex v to this graph. method addVertex(v: T) requires v !in V ensures E == old(E) && V == old(V) + {v} { V := V + {v}; } // Adds a new edge (u, v) to this graph. method addEdge(u: T, v: T) requires u in V && v in V && (u, v) !in E && u != v ensures V == old(V) && E == old(E) + {(u, v)} { E := E + {(u, v)}; } // Obtains the set of vertices adjacent to a given vertex v. function getAdj(v: T): set<T> requires v in V { set e | e in E && e.0 == v :: e.1 } // Removes a vertex v and all the edges incident on v from the graph. method removeVertex(v: T) requires v in V ensures V == old(V) - {v} ensures E == set e | e in old(E) && e.0 != v && e.1 != v { V := V - {v}; E := set e | e in E && e.0 != v && e.1 != v; } // Collapses a subset C of vertices to a single vertex v (belonging to C). // All vertices in C are removed from the graph, except v. // Edges that connect vertices in C are removed from the graph. // In all other edges, vertices belonging to C are replaced by v. method collapseVertices(C: set<T>, v: T) requires v in C && C <= V ensures V == old(V) - C + {v} ensures E == set e | e in old(E) && (e.0 !in C || e.1 !in C) :: (if e.0 in C then v else e.0, if e.1 in C then v else e.1) { V := V - C + {v}; E := set e | e in E && (e.0 !in C || e.1 !in C) :: (if e.0 in C then v else e.0, if e.1 in C then v else e.1); } } method testGraph() { var G := new Graph<int>(); assert G.E == {} && G.V == {}; G.addVertex(1); G.addVertex(2); G.addVertex(3); G.addVertex(4); assert G.V == {1, 2, 3, 4}; G.addEdge(1, 2); G.addEdge(1, 3); G.addEdge(2, 3); G.addEdge(4, 1); assert G.E == {(1, 2), (1, 3), (2, 3), (4, 1)}; assert G.getAdj(1) == {2, 3}; G.collapseVertices({1, 2, 3}, 3); assert G.V == {3, 4} && G.E == {(4, 3)}; }
// Simple directed graph with vertices of any type T. class {:autocontracts} Graph<T(==)> { var V: set<T>; // vertex-set var E: set<(T, T)>; // edge-set // Class invariant. ghost predicate Valid() { // edges must refer to vertices that belong to the vertex-set // and self-loops (edges connecting a vertex to itself) are not allowed forall e :: e in E ==> e.0 in V && e.1 in V && e.0 != e.1 } // Creates an empty graph. constructor () ensures V == {} && E == {} { V:= {}; E := {}; } // Adds a new vertex v to this graph. method addVertex(v: T) requires v !in V ensures E == old(E) && V == old(V) + {v} { V := V + {v}; } // Adds a new edge (u, v) to this graph. method addEdge(u: T, v: T) requires u in V && v in V && (u, v) !in E && u != v ensures V == old(V) && E == old(E) + {(u, v)} { E := E + {(u, v)}; } // Obtains the set of vertices adjacent to a given vertex v. function getAdj(v: T): set<T> requires v in V { set e | e in E && e.0 == v :: e.1 } // Removes a vertex v and all the edges incident on v from the graph. method removeVertex(v: T) requires v in V ensures V == old(V) - {v} ensures E == set e | e in old(E) && e.0 != v && e.1 != v { V := V - {v}; E := set e | e in E && e.0 != v && e.1 != v; } // Collapses a subset C of vertices to a single vertex v (belonging to C). // All vertices in C are removed from the graph, except v. // Edges that connect vertices in C are removed from the graph. // In all other edges, vertices belonging to C are replaced by v. method collapseVertices(C: set<T>, v: T) requires v in C && C <= V ensures V == old(V) - C + {v} ensures E == set e | e in old(E) && (e.0 !in C || e.1 !in C) :: (if e.0 in C then v else e.0, if e.1 in C then v else e.1) { V := V - C + {v}; E := set e | e in E && (e.0 !in C || e.1 !in C) :: (if e.0 in C then v else e.0, if e.1 in C then v else e.1); } } method testGraph() { var G := new Graph<int>(); G.addVertex(1); G.addVertex(2); G.addVertex(3); G.addVertex(4); G.addEdge(1, 2); G.addEdge(1, 3); G.addEdge(2, 3); G.addEdge(4, 1); G.collapseVertices({1, 2, 3}, 3); }
123
DafnyProjects_tmp_tmp2acw_s4s_Power.dfy
/* * 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; }
124
DafnyProjects_tmp_tmp2acw_s4s_RawSort.dfy
/** * 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]; }
/** * 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); }
125
DafnyProjects_tmp_tmp2acw_s4s_findMax.dfy
/* * 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; }
/* * 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); }
126
DafnyProjects_tmp_tmp2acw_s4s_longestPrefix.dfy
// 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; }
// 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); }
127
DafnyProjects_tmp_tmp2acw_s4s_partitionOddEven.dfy
// 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]; }
// 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); }
128
DafnyProjects_tmp_tmp2acw_s4s_sqrt.dfy
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); }
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); }
129
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_A2_Q1_trimmed copy - 副本.dfy
ghost function Count(hi: nat, s:seq<int>): int requires 0 <= hi <= |s| decreases hi { if hi == 0 then 0 else if s[hi-1]%2 == 0 then 1 + Count(hi-1, s) else Count(hi-1, s) } method FooCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) decreases CountIndex modifies b ensures p == Count(CountIndex,a) { assert CountIndex == 0 || (|a| == b.Length && 1<=CountIndex <= |a|); assert CountIndex == 0 || (|a| == b.Length && 0<=CountIndex -1 <= |a|); assert CountIndex!=0 ==> |a| == b.Length && 0<=CountIndex -1 <= |a|; assert CountIndex == 0 ==> true && CountIndex != 0 ==> |a| == b.Length && 0<=CountIndex -1 <= |a|; if CountIndex == 0{ assert true; assert 0 == 0; assert 0 == Count(0,a); p :=0; assert p == Count(CountIndex,a); } else{ assert |a| == b.Length && 0<=CountIndex-1 <=|a|; assert (a[CountIndex-1]%2 ==0 ==>|a| == b.Length && 0<= CountIndex -1 <|a| && 1+ Count(CountIndex-1,a) == Count(CountIndex,a)) && (a[CountIndex-1]%2 !=0 ==> |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a)); if a[CountIndex-1]%2==0{ assert |a| == b.Length && 0<= CountIndex -1 <|a| && 1+ Count(CountIndex-1,a) == Count(CountIndex,a); var d := FooCount(CountIndex -1,a,b); assert d+1 == Count(CountIndex,a); p:= d+1; assert p == Count(CountIndex,a); }else{ assert |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a); assert |a| == b.Length && 0<= CountIndex -1 <|a| && forall p'::p' ==Count(CountIndex-1,a) ==> p'==Count(CountIndex,a); var d:= FooCount(CountIndex -1,a,b); assert d == Count(CountIndex,a); p:= d; assert p == Count(CountIndex,a); } b[CountIndex-1] := p; assert p == Count(CountIndex,a); } } method FooPreCompute(a:array<int>,b:array<int>) requires a.Length == b.Length modifies b { var CountIndex := 1; while CountIndex != a.Length + 1 decreases a.Length + 1 - CountIndex invariant 1 <= CountIndex <= a.Length +1; { assert (CountIndex == 0 || (a.Length == b.Length && 1 <= CountIndex <= a.Length)) && forall a'::a' ==Count(CountIndex,a[..]) ==> a' ==Count(CountIndex,a[..]); var p := FooCount(CountIndex,a[..],b); assert 1<= CountIndex <= a.Length; assert 1 <= CountIndex + 1<= a.Length +1; CountIndex := CountIndex +1; assert 1 <= CountIndex <= a.Length +1; } } method ComputeCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) decreases CountIndex modifies b ensures p == Count(CountIndex,a) { if CountIndex == 0{ p :=0; } else{ if a[CountIndex-1]%2==0{ var d := ComputeCount(CountIndex -1,a,b); p:= d+1; }else{ var d:= ComputeCount(CountIndex -1,a,b); p:= d; } b[CountIndex-1] := p; } } method PreCompute(a:array<int>,b:array<int>)returns(p:nat) requires a.Length == b.Length modifies b ensures (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) && forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) { assert (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) && (forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) ); p := ComputeCount(b.Length,a[..],b); } method Evens(a:array<int>) returns (c:array2<int>) // modifies c // ensures invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 { c := new int[a.Length,a.Length]; var b := new int[a.Length]; var foo := PreCompute(a,b); var m := 0; while m != a.Length decreases a.Length - m modifies c invariant 0 <= m <= a.Length invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i>0 ==> c[i,j] == b[j] - b[i-1] invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i == 0 ==> c[i,j] == b[j] { var n := 0; while n != a.Length decreases a.Length - n modifies c invariant 0 <= n <= a.Length invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 invariant forall j:: 0 <= j <n ==> j < m ==> c[m,j] == 0 invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i>0 ==> c[i,j] == b[j] - b[i-1] invariant forall j:: 0 <= j <n ==> j>=m ==> m>0 ==> c[m,j] == b[j] - b[m-1] invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j>=i ==> i == 0 ==> c[i,j] == b[j] invariant forall j:: 0 <= j <n ==> j>=m ==> m==0 ==> c[m,j] == b[j] { if (n < m) { c[m,n] := 0; }else { if m > 0 { c[m,n] := b[n] - b[m-1]; }else{ c[m,n] := b[n]; } } n := n + 1; } m := m + 1; } } method Mult(x:int, y:int) returns (r:int) requires x>= 0 && y>=0 decreases x ensures r == x*y { if x==0 { r:=0; }else{ assert x-1>= 0 && y>= 0&& (x-1)*y + y== x*y; var z:= Mult(x-1,y); assert z+y == x*y; r:=z+y; assert r == x*y; } }
ghost function Count(hi: nat, s:seq<int>): int requires 0 <= hi <= |s| { if hi == 0 then 0 else if s[hi-1]%2 == 0 then 1 + Count(hi-1, s) else Count(hi-1, s) } method FooCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) modifies b ensures p == Count(CountIndex,a) { if CountIndex == 0{ p :=0; } else{ (a[CountIndex-1]%2 !=0 ==> |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a)); if a[CountIndex-1]%2==0{ var d := FooCount(CountIndex -1,a,b); p:= d+1; }else{ var d:= FooCount(CountIndex -1,a,b); p:= d; } b[CountIndex-1] := p; } } method FooPreCompute(a:array<int>,b:array<int>) requires a.Length == b.Length modifies b { var CountIndex := 1; while CountIndex != a.Length + 1 { var p := FooCount(CountIndex,a[..],b); CountIndex := CountIndex +1; } } method ComputeCount(CountIndex:nat, a:seq<int>,b:array<int>) returns (p:nat) requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|) modifies b ensures p == Count(CountIndex,a) { if CountIndex == 0{ p :=0; } else{ if a[CountIndex-1]%2==0{ var d := ComputeCount(CountIndex -1,a,b); p:= d+1; }else{ var d:= ComputeCount(CountIndex -1,a,b); p:= d; } b[CountIndex-1] := p; } } method PreCompute(a:array<int>,b:array<int>)returns(p:nat) requires a.Length == b.Length modifies b ensures (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) && forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) { && (forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) ); p := ComputeCount(b.Length,a[..],b); } method Evens(a:array<int>) returns (c:array2<int>) // modifies c // ensures invariant forall i,j:: 0 <=i <m && 0 <= j < a.Length ==> j<i ==> c[i,j] == 0 { c := new int[a.Length,a.Length]; var b := new int[a.Length]; var foo := PreCompute(a,b); var m := 0; while m != a.Length modifies c { var n := 0; while n != a.Length modifies c { if (n < m) { c[m,n] := 0; }else { if m > 0 { c[m,n] := b[n] - b[m-1]; }else{ c[m,n] := b[n]; } } n := n + 1; } m := m + 1; } } method Mult(x:int, y:int) returns (r:int) requires x>= 0 && y>=0 ensures r == x*y { if x==0 { r:=0; }else{ var z:= Mult(x-1,y); r:=z+y; } }
130
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_MaxSum.dfy
method MaxSum(x:int, y:int) returns (s:int, m:int) ensures s == x+y ensures (m == x || m == y) && x <= m && y <= m { s := x+y; if x > y{ m := x; } else if y > x{ m := y; } else { m := x; } assert m >= y; } method Main() { var m, n := 4,5; var a,b := MaxSum(m,n); print "Search return a is ", a,",,,,, b is ", b, "\n"; }
method MaxSum(x:int, y:int) returns (s:int, m:int) ensures s == x+y ensures (m == x || m == y) && x <= m && y <= m { s := x+y; if x > y{ m := x; } else if y > x{ m := y; } else { m := x; } } method Main() { var m, n := 4,5; var a,b := MaxSum(m,n); print "Search return a is ", a,",,,,, b is ", b, "\n"; }
131
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_Week4__LinearSearch.dfy
method LinearSeach0<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) { n := 0; while n != a.Length invariant 0 <= n <= a.Length { if P(a[n]) {return;} n := n + 1; } } predicate P(n: int) { n % 2 == 0 } method TestLinearSearch() { /* var a := new int[3][44,2,56]; var n := LinearSeach0<int>(a,P); assert n == 1 || n == 2 || n == 3 || n == 0; */ var a := new int[3][1,2,3]; var n := LinearSeach1<int>(a,P); assert n == 1 || n == 2 || n==3 || n == 0; } method LinearSeach1<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> !P(a[i]) { n := 0; while n != a.Length invariant 0 <= n <= a.Length invariant forall i :: 0<=i<n ==> !P(a[i]) { if P(a[n]) {return;} n := n + 1; } }
method LinearSeach0<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) { n := 0; while n != a.Length { if P(a[n]) {return;} n := n + 1; } } predicate P(n: int) { n % 2 == 0 } method TestLinearSearch() { /* var a := new int[3][44,2,56]; var n := LinearSeach0<int>(a,P); */ var a := new int[3][1,2,3]; var n := LinearSeach1<int>(a,P); } method LinearSeach1<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> !P(a[i]) { n := 0; while n != a.Length { if P(a[n]) {return;} n := n + 1; } }
132
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week4_tute_ex4.dfy
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; }
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; }
133
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week5_ComputePower.dfy
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; } }
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; } }
134
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_a3 copy 2.dfy
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; } }
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; } }
135
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_a3_search_findPositionOfIndex.dfy
method FindPositionOfElement(a:array<int>,Element:nat,n1:nat,s1:seq<int>) returns (Position:int,Count:nat) requires n1 == |s1| && 0 <= n1 <= a.Length requires forall i:: 0<= i < |s1| ==> a[i] == s1[i] ensures Position == -1 || Position >= 1 ensures |s1| != 0 && Position >= 1 ==> exists i:: 0 <= i < |s1| && s1[i] == Element { Count := 0; Position := 0; // assert forall i:: 0<= i <|s1| ==> a[n1-1-i] == s1[n1-1-i]; // assert forall i:: 0<= i <|s1| ==> a[n1-1-i]!= Element; while Count != n1 decreases n1 - Count invariant |s1|!=0 && Position >= 1 ==> exists i:: 0 <= i < n1 && a[i] == Element invariant 0 <= Count <= n1 invariant Position >=1 ==> forall i:: 0<= i <Count ==> a[i] != Element invariant Position == -1 ==> forall i:: 0<= i < n1 ==> a[i] != Element { if a[n1-1-Count] == Element { Position := Count + 1; //assert Count >= 1 ==> a[Count -1] != Element; //assert a[Count] == Element; return Position,Count; } Count := Count + 1; } assert Position != -1 ==> true; //assert Position != -1 ==> forall i:: 0<= i < Count ==> a[i] != Element; Position := -1; // assert Position == -1 ==> forall i:: 0<= i < n1 ==> a[i] != Element; //assert exists i:: 0 <= i < |s1| && a[i] == Element; assert Position == -1; } method Main() { var a := new int[5]; var b := [1,2,3,4]; a[0],a[1],a[2],a[3]:= 1,2,3,4; var n1 := |b|; var Element := 5; var Position, Count; Position, Count := FindPositionOfElement(a,Element,n1,b); print "position is ",Position; }
method FindPositionOfElement(a:array<int>,Element:nat,n1:nat,s1:seq<int>) returns (Position:int,Count:nat) requires n1 == |s1| && 0 <= n1 <= a.Length requires forall i:: 0<= i < |s1| ==> a[i] == s1[i] ensures Position == -1 || Position >= 1 ensures |s1| != 0 && Position >= 1 ==> exists i:: 0 <= i < |s1| && s1[i] == Element { Count := 0; Position := 0; // assert forall i:: 0<= i <|s1| ==> a[n1-1-i] == s1[n1-1-i]; // assert forall i:: 0<= i <|s1| ==> a[n1-1-i]!= Element; while Count != n1 { if a[n1-1-Count] == Element { Position := Count + 1; //assert Count >= 1 ==> a[Count -1] != Element; //assert a[Count] == Element; return Position,Count; } Count := Count + 1; } //assert Position != -1 ==> forall i:: 0<= i < Count ==> a[i] != Element; Position := -1; // assert Position == -1 ==> forall i:: 0<= i < n1 ==> a[i] != Element; //assert exists i:: 0 <= i < |s1| && a[i] == Element; } method Main() { var a := new int[5]; var b := [1,2,3,4]; a[0],a[1],a[2],a[3]:= 1,2,3,4; var n1 := |b|; var Element := 5; var Position, Count; Position, Count := FindPositionOfElement(a,Element,n1,b); print "position is ",Position; }
136
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week10_BoundedQueue_01.dfy
class BoundedQueue<T(0)> { // abstract state ghost var contents: seq<T> // the contents of the bounded queue ghost var N: nat // the (maximum) size of the bounded queue ghost var Repr: set<object> // concrete state var data: array<T> var wr: nat var rd: nat ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr && |contents| <= N { this in Repr && data in Repr && data.Length == N + 1 && wr <= N && rd <= N && contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr] } constructor (N: nat) ensures Valid() && fresh(Repr) ensures contents == [] && this.N == N { contents := []; this.N := N; data := new T[N+1]; // requires T to have default initial value rd, wr := 0, 0; Repr := {this, data}; } method Insert(x:T) requires Valid() requires |contents| != N modifies Repr ensures contents == old(contents) + [x] ensures N == old(N) ensures Valid() && fresh(Repr - old(Repr)) { contents := old(contents) + [x]; data[wr] := x; assert (wr == data.Length -1 ==> contents == if rd <= 0 then data[rd..0] else data[rd..] + data[..0]) && (wr!= data.Length -1 ==> contents == if rd <= wr+1 then data[rd..wr+1] else data[rd..] + data[..wr+1]); if wr == data.Length -1 { assert contents == if rd <= 0 then data[rd..0] else data[rd..] + data[..0]; wr := 0; assert contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr]; } else { assert contents == if rd <= wr+1 then data[rd..wr+1] else data[rd..] + data[..wr+1]; wr := wr + 1; assert contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr]; } assert contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr]; } method Remove() returns (x:T) requires Valid() requires |contents| != 0 modifies Repr ensures contents == old(contents[1..]) && old(contents[0]) == x ensures N == old(N) ensures Valid() && fresh(Repr - old(Repr)) { contents := contents[1..]; x := data[rd]; if rd == data.Length - 1 { rd := 0; } else { rd := rd + 1; } } }
class BoundedQueue<T(0)> { // abstract state ghost var contents: seq<T> // the contents of the bounded queue ghost var N: nat // the (maximum) size of the bounded queue ghost var Repr: set<object> // concrete state var data: array<T> var wr: nat var rd: nat ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr && |contents| <= N { this in Repr && data in Repr && data.Length == N + 1 && wr <= N && rd <= N && contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr] } constructor (N: nat) ensures Valid() && fresh(Repr) ensures contents == [] && this.N == N { contents := []; this.N := N; data := new T[N+1]; // requires T to have default initial value rd, wr := 0, 0; Repr := {this, data}; } method Insert(x:T) requires Valid() requires |contents| != N modifies Repr ensures contents == old(contents) + [x] ensures N == old(N) ensures Valid() && fresh(Repr - old(Repr)) { contents := old(contents) + [x]; data[wr] := x; && (wr!= data.Length -1 ==> contents == if rd <= wr+1 then data[rd..wr+1] else data[rd..] + data[..wr+1]); if wr == data.Length -1 { wr := 0; } else { wr := wr + 1; } } method Remove() returns (x:T) requires Valid() requires |contents| != 0 modifies Repr ensures contents == old(contents[1..]) && old(contents[0]) == x ensures N == old(N) ensures Valid() && fresh(Repr - old(Repr)) { contents := contents[1..]; x := data[rd]; if rd == data.Length - 1 { rd := 0; } else { rd := rd + 1; } } }
137
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week10_ExtensibleArray.dfy
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; } } }
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; } } }
138
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week8_CheckSumCalculator.dfy
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; }
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; }
139
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week8_CoffeeMaker2.dfy
class Grinder { ghost var hasBeans: bool ghost var Repr: set<object> ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr constructor() ensures Valid() && fresh(Repr) && !hasBeans function Ready(): bool requires Valid() reads Repr ensures Ready() == hasBeans method AddBeans() requires Valid() modifies Repr ensures Valid() && hasBeans && fresh(Repr-old(Repr)) method Grind() requires Valid() && hasBeans modifies Repr ensures Valid() && fresh(Repr-old(Repr)) } class WaterTank { ghost var waterLevel: nat ghost var Repr: set<object> ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr constructor() ensures Valid() && fresh(Repr) && waterLevel == 0 function Level(): nat requires Valid() reads Repr ensures Level() == waterLevel method Fill() requires Valid() modifies Repr ensures Valid() && fresh(Repr-old(Repr)) && waterLevel == 10 method Use() requires Valid() && waterLevel != 0 modifies Repr ensures Valid() && fresh(Repr-old(Repr)) && waterLevel == old(Level()) - 1 } class CoffeeMaker { var g: Grinder var w: WaterTank ghost var ready: bool ghost var Repr: set<object> ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr { this in Repr && g in Repr && w in Repr && g.Repr <= Repr && w.Repr <= Repr && g.Valid() && w.Valid() && this !in g.Repr && this !in w.Repr && w.Repr !! g.Repr && ready == (g.hasBeans && w.waterLevel != 0) } constructor() ensures Valid() && fresh(Repr) { g := new Grinder(); w := new WaterTank(); ready := false; new; Repr := {this, g, w} + g.Repr + w.Repr; } predicate Ready() requires Valid() reads Repr ensures Ready() == ready { g.Ready() && w.Level() != 0 } method Restock() requires Valid() modifies Repr ensures Valid() && Ready() && fresh(Repr - old(Repr)) { assert w.Valid(); g.AddBeans(); assert w.Valid(); w.Fill(); ready := true; Repr := Repr + g.Repr + w.Repr; } method Dispense() requires Valid() && Ready() modifies Repr ensures Valid() && fresh(Repr - old(Repr)) { g.Grind(); w.Use(); ready := g.hasBeans && w.waterLevel != 0; Repr := Repr + g.Repr + w.Repr; } } method CoffeeTestHarness() { var cm := new CoffeeMaker(); cm.Restock(); cm.Dispense(); }
class Grinder { ghost var hasBeans: bool ghost var Repr: set<object> ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr constructor() ensures Valid() && fresh(Repr) && !hasBeans function Ready(): bool requires Valid() reads Repr ensures Ready() == hasBeans method AddBeans() requires Valid() modifies Repr ensures Valid() && hasBeans && fresh(Repr-old(Repr)) method Grind() requires Valid() && hasBeans modifies Repr ensures Valid() && fresh(Repr-old(Repr)) } class WaterTank { ghost var waterLevel: nat ghost var Repr: set<object> ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr constructor() ensures Valid() && fresh(Repr) && waterLevel == 0 function Level(): nat requires Valid() reads Repr ensures Level() == waterLevel method Fill() requires Valid() modifies Repr ensures Valid() && fresh(Repr-old(Repr)) && waterLevel == 10 method Use() requires Valid() && waterLevel != 0 modifies Repr ensures Valid() && fresh(Repr-old(Repr)) && waterLevel == old(Level()) - 1 } class CoffeeMaker { var g: Grinder var w: WaterTank ghost var ready: bool ghost var Repr: set<object> ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr { this in Repr && g in Repr && w in Repr && g.Repr <= Repr && w.Repr <= Repr && g.Valid() && w.Valid() && this !in g.Repr && this !in w.Repr && w.Repr !! g.Repr && ready == (g.hasBeans && w.waterLevel != 0) } constructor() ensures Valid() && fresh(Repr) { g := new Grinder(); w := new WaterTank(); ready := false; new; Repr := {this, g, w} + g.Repr + w.Repr; } predicate Ready() requires Valid() reads Repr ensures Ready() == ready { g.Ready() && w.Level() != 0 } method Restock() requires Valid() modifies Repr ensures Valid() && Ready() && fresh(Repr - old(Repr)) { g.AddBeans(); w.Fill(); ready := true; Repr := Repr + g.Repr + w.Repr; } method Dispense() requires Valid() && Ready() modifies Repr ensures Valid() && fresh(Repr - old(Repr)) { g.Grind(); w.Use(); ready := g.hasBeans && w.waterLevel != 0; Repr := Repr + g.Repr + w.Repr; } } method CoffeeTestHarness() { var cm := new CoffeeMaker(); cm.Restock(); cm.Dispense(); }
140
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week9_lemma.dfy
method AssignmentsToMark(students:int, tutors: int) returns (r:int) requires students > 0 && tutors > 1 ensures r < students { assert students > 0 && tutors > 1; assert students > 0 && tutors > 1 && true; assert students > 0 && tutors > 1 && students/tutors < students ==> students/tutors < students; DivisionLemma(students,tutors); assert students/tutors < students; r:= students/tutors; assert r< students; calc { //true; 1/tutors < 1; students/tutors < students; } } lemma DivisionLemma(n:int,d:int) requires n > 0 && d>1 ensures n/d < n method AssignmentsToMarkOne(students:int, tutors: int) returns (r:int) requires students > 0 && tutors > 1 ensures r < students { r:= students/tutors; calc == { true; 1/tutors < 1; students/tutors < students; } } lemma CommonElement(a:array<nat>, b:array<nat>) requires a.Length> 0 && b.Length > 0 && a[0] == b[0] ensures multiset(a[..]) * multiset(b[..]) == multiset([a[0]]) + multiset(a[1..]) * multiset(b[1..]) //ensures multiset{a[..]} * multiset{b[..]} == multiset([a[0]]) + multiset{a[1..]} * multiset{b[1..]} /* { var E := multiset{a[0]}; calc =={ multiset(a[..]) * multiset(b[..]); assert (a[..] == [a[0]] + a[1..]) && (b[..] == [b[0]] + b[1..]); (E+ multiset(a[1..])) * (E + multiset(a[1..])); E + multiset(a[1..]) * multiset(b[1..]); } }*/
method AssignmentsToMark(students:int, tutors: int) returns (r:int) requires students > 0 && tutors > 1 ensures r < students { DivisionLemma(students,tutors); r:= students/tutors; calc { //true; 1/tutors < 1; students/tutors < students; } } lemma DivisionLemma(n:int,d:int) requires n > 0 && d>1 ensures n/d < n method AssignmentsToMarkOne(students:int, tutors: int) returns (r:int) requires students > 0 && tutors > 1 ensures r < students { r:= students/tutors; calc == { true; 1/tutors < 1; students/tutors < students; } } lemma CommonElement(a:array<nat>, b:array<nat>) requires a.Length> 0 && b.Length > 0 && a[0] == b[0] ensures multiset(a[..]) * multiset(b[..]) == multiset([a[0]]) + multiset(a[1..]) * multiset(b[1..]) //ensures multiset{a[..]} * multiset{b[..]} == multiset([a[0]]) + multiset{a[1..]} * multiset{b[1..]} /* { var E := multiset{a[0]}; calc =={ multiset(a[..]) * multiset(b[..]); (E+ multiset(a[1..])) * (E + multiset(a[1..])); E + multiset(a[1..]) * multiset(b[1..]); } }*/
141
Dafny_ProgrammingLanguages_tmp_tmp82_e0kji_ExtraCredit.dfy
datatype Exp = Const(int) | Var(string) | Plus(Exp, Exp) | Mult(Exp, Exp) function eval(e:Exp, store:map<string, int>):int { match(e) case Const(n) => n case Var(s) => if(s in store) then store[s] else -1 case Plus(e1, e2) => eval(e1, store) + eval(e2, store) case Mult(e1, e2) => eval(e1, store) * eval(e2, store) } //fill this function in to make optimizeFeatures work function optimize(e:Exp):Exp { match e case Mult(Const(0), e) => Const(0) case Mult(e, Const(0)) => Const(0) case Mult(Const(1), e) => e case Mult(e, Const(1)) => e case Mult(Const(n1), Const(n2)) => Const(n1*n2) case Plus(Const(0), e) => e case Plus(e, Const(0)) => e case Plus(Const(n1), Const(n2)) => Const(n1+ n2) case e => e } //as you write optimize this will become unproved //you must write proof code so that Dafny can prove this method optimizeCorrect(e:Exp, s:map<string, int>) ensures eval(e,s) == eval(optimize(e), s) { } method optimizeFeatures() { assert( optimize(Mult(Var("x"), Const(0))) == Const(0) ); assert( optimize(Mult(Var("x"), Const(1))) == Var("x") ); assert( optimize(Mult(Const(0), Var("x"))) == Const(0) ); assert( optimize(Mult(Const(1), Var("x"))) == Var("x") ); assert( optimize(Plus(Const(0), Var("x"))) == Var("x") ); assert( optimize(Plus(Var("x"), Const(0))) == Var("x") ); assert( optimize(Plus(Const(3),Const(4))) == Const(7) ); assert( optimize(Mult(Const(3),Const(4))) == Const(12) ); assert( optimize(Plus(Plus(Var("x"), Var("y")), Const(0))) == Plus(Var("x"), Var("y")) ); }
datatype Exp = Const(int) | Var(string) | Plus(Exp, Exp) | Mult(Exp, Exp) function eval(e:Exp, store:map<string, int>):int { match(e) case Const(n) => n case Var(s) => if(s in store) then store[s] else -1 case Plus(e1, e2) => eval(e1, store) + eval(e2, store) case Mult(e1, e2) => eval(e1, store) * eval(e2, store) } //fill this function in to make optimizeFeatures work function optimize(e:Exp):Exp { match e case Mult(Const(0), e) => Const(0) case Mult(e, Const(0)) => Const(0) case Mult(Const(1), e) => e case Mult(e, Const(1)) => e case Mult(Const(n1), Const(n2)) => Const(n1*n2) case Plus(Const(0), e) => e case Plus(e, Const(0)) => e case Plus(Const(n1), Const(n2)) => Const(n1+ n2) case e => e } //as you write optimize this will become unproved //you must write proof code so that Dafny can prove this method optimizeCorrect(e:Exp, s:map<string, int>) ensures eval(e,s) == eval(optimize(e), s) { } method optimizeFeatures() { }
142
Dafny_Programs_tmp_tmp99966ew4_binary_search.dfy
predicate sorted(a: array<int>) requires a != null reads a { forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] } method BinarySearch(a: array<int>, value: int) returns (index: int) requires a != null && 0 <= a.Length && sorted(a) ensures 0 <= index ==> index < a.Length && a[index] == value ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != value { var low, high := 0, a.Length; while low < high invariant 0 <= low <= high <= a.Length invariant forall i :: 0 <= i < a.Length && !(low <= i < high) ==> a[i] != value decreases high - low { var mid := (low + high) / 2; if a[mid] < value { low := mid + 1; } else if value < a[mid] { high := mid; } else { return mid; } } return -1; }
predicate sorted(a: array<int>) requires a != null reads a { forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] } method BinarySearch(a: array<int>, value: int) returns (index: int) requires a != null && 0 <= a.Length && sorted(a) ensures 0 <= index ==> index < a.Length && a[index] == value ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != value { var low, high := 0, a.Length; while low < high 0 <= i < a.Length && !(low <= i < high) ==> a[i] != value { var mid := (low + high) / 2; if a[mid] < value { low := mid + 1; } else if value < a[mid] { high := mid; } else { return mid; } } return -1; }
143
Dafny_Programs_tmp_tmp99966ew4_lemma.dfy
lemma SkippingLemma(a : array<int>, j : int) requires a != null requires forall i :: 0 <= i < a.Length ==> 0 <= a[i] requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i] requires 0 <= j < a.Length ensures forall k :: j <= k < j + a[j] && k < a.Length ==> a[k] != 0 { var i := j; while i < j + a[j] && i < a.Length decreases j + a[j] - i invariant i < a.Length ==> a[j] - (i-j) <= a[i] invariant forall k :: j <= k < i && k < a.Length ==> a[k] != 0 { i := i + 1; } } method FindZero(a: array<int>) returns (index: int) requires a != null requires forall i :: 0 <= i < a.Length ==> 0 <= a[i] requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i] ensures index < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != 0 ensures 0 <= index ==> index < a.Length && a[index] == 0 { index := 0; while index < a.Length decreases a.Length - index invariant 0 <= index invariant forall k :: 0 <= k < index && k < a.Length ==> a[k] != 0 { if a[index] == 0 { return; } SkippingLemma(a, index); index := index + a[index]; } index := -1; }
lemma SkippingLemma(a : array<int>, j : int) requires a != null requires forall i :: 0 <= i < a.Length ==> 0 <= a[i] requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i] requires 0 <= j < a.Length ensures forall k :: j <= k < j + a[j] && k < a.Length ==> a[k] != 0 { var i := j; while i < j + a[j] && i < a.Length { i := i + 1; } } method FindZero(a: array<int>) returns (index: int) requires a != null requires forall i :: 0 <= i < a.Length ==> 0 <= a[i] requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i] ensures index < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != 0 ensures 0 <= index ==> index < a.Length && a[index] == 0 { index := 0; while index < a.Length { if a[index] == 0 { return; } SkippingLemma(a, index); index := index + a[index]; } index := -1; }
144
Dafny_Programs_tmp_tmp99966ew4_mymax.dfy
method Max(a: int, b:int) returns (c: int) ensures c >= a && c>= b { if (a < b) { c := b; } else { c := a; } assert a <= c && b <= c; } method Testing() { var v := Max(2, 3); assert v >= 3; }
method Max(a: int, b:int) returns (c: int) ensures c >= a && c>= b { if (a < b) { c := b; } else { c := a; } } method Testing() { var v := Max(2, 3); }
145
Dafny_Programs_tmp_tmp99966ew4_trig.dfy
predicate P(x: int) predicate Q(x: int) method test() requires forall x {:trigger P(x)} :: P(x) && Q(x) ensures Q(0) { assert P(0); }
predicate P(x: int) predicate Q(x: int) method test() requires forall x {:trigger P(x)} :: P(x) && Q(x) ensures Q(0) { }
146
Dafny_Verify_tmp_tmphq7j0row_AI_agent_validation_examples.dfy
function Power(n: nat): nat { if n == 0 then 1 else 2 * Power(n - 1) } method ComputePower(N: int) returns (y: nat) requires N >= 0 ensures y == Power(N) { y := 1; var x := 0; while x != N invariant 0 <= x <= N invariant y == Power(x) decreases N - x { x, y := x + 1, y + y; } } // Original davinci-003 completion: // method ComputePower1(N: int) returns (y: nat) requires N >= 0 // ensures y == Power(N) // { // y := 1; // var x := 0; // while x != N // decreases N - x // invariant 0 <= x <= N // invariant y == Power(x) // { // x, y := x + 1, y + y; // } // } // Fine_tuned davinci-003 completion: // method ComputePower1(N: int) returns (y: nat) requires N >= 0 // ensures y == Power(N) // { // y := 1; // var x := 0; // while x != N // decreases N - x // invariant 0 <= x <= N // invariant y == Power(x) // { // x, y := x + 1, y + y; // } // } method Max(a: array<nat>) returns (m: int) ensures forall i :: 0 <= i < a.Length ==> a[i] <= m ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i] { m := 0; var n := 0; while n != a.Length invariant 0 <= n <= a.Length invariant forall i :: 0 <= i < n ==> a[i] <= m invariant (m == 0 && n == 0) || exists i :: 0 <= i < n && m == a[i] { if m < a[n] { m := a[n]; } n := n + 1; } } // Original davinci-003 completion: // method Max(a: array<nat>) returns (m: int) // requires a.Length > 0 // ensures forall i :: 0 <= i < a.Length ==> a[i] <= m // ensures exists i :: 0 <= i < a.Length && m == a[i] // { // m := a[0]; // var n := 1; // while n != a.Length // { // if m < a[n] { // m := a[n]; // } // n := n + 1; // // Loop invariant: 0 <= n <= a.Length && forall i :: 0 <= i < n ==> a[i] <= m // } // } // Fine_tuned davinci-003 completion: // method Max1(a: array<nat>) returns (m: int) // ensures forall i :: 0 <= i < a.Length ==> a[i] <= m // ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i] // { // m := 0; // var n := 0; // while n != a.Length // invariant 0 <= n <= a.Length // invariant forall i :: 0 <= i < n ==> a[i] <= m // { // if m < a[n] { // m := a[n]; // } // n := n + 1; // } // } method Cube(n: nat) returns (c: nat) ensures c == n * n * n { c := 0; var i := 0; var k := 1; var m := 6; while i != n invariant 0 <= i <= n invariant c == i * i * i invariant k == 3*i*i + 3*i + 1 invariant m == 6 * i + 6 { c, k, m := c + k, k + m, m + 6; i := i + 1; } } // Original davinci-003 completion: // method Cube(n: nat) returns (c: nat) // ensures c == n * n * n // { // c := 0; // var i := 0; // var k := 1; // var m := 6; // // Loop invariant: c = i^3 // while i != n // { // c, k, m := c + k, k + m, m + 6; // i := i + 1; // } // } // Fine_tuned davinci-003 completion: // method Cube1(n: nat) returns (c: nat) // ensures c == n * n * n // { // c := 0; // var i := 0; // var k := 1; // var m := 6; // while i != n // invariant 0 <= i <= n // invariant c == i * k * m // { // c, k, m := c + k, k + m, m + 6; // i := i + 1; // } // } method IncrementMatrix(a: array2<int>) modifies a ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 { var m := 0; while m != a.Length0 invariant 0 <= m <= a.Length0 invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 invariant forall i, j :: m <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) { var n := 0; while n != a.Length1 invariant 0 <= n <= a.Length1 invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 invariant forall i, j :: m < i < a.Length0 && 0 <= j < a.Length1==> a[i,j] == old(a[i,j]) invariant forall j :: 0 <= j < n ==> a[m,j] == old(a[m,j])+1 invariant forall j :: n <= j < a.Length1 ==> a[m,j] == old(a[m,j]) { a[m,n] := a[m,n] + 1; n := n + 1; } m := m + 1; } } // Original davinci-003 completion: // method IncrementMatrix(a: array2<int>) // modifies a // ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // var m := 0; // while m != a.Length0 // { // var n := 0; // while n != a.Length1 // { // // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> a[i,j] == old(a[i,j]) + 1 // a[m,n] := a[m,n] + 1; // n := n + 1; // } // m := m + 1; // } // } // Fine_tuned davinci-003 completion: // method IncrementMatrix1(a: array2<int>) // modifies a // ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // var m := 0; // while m != a.Length0 // invariant 0 <= m <= a.Length0 && 0 <= j < a.Length1 <= a.Length2 // invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // var n := 0; // while n != a.Length1 // invariant 0 <= n <= a.Length2 // invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // a[m,n] := a[m,n] + 1; // n := n + 1; // } // m := m + 1; // } // } method CopyMatrix(src: array2, dst: array2) requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 modifies dst ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) { var m := 0; while m != src.Length0 invariant 0 <= m <= src.Length0 invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j]) { var n := 0; while n != src.Length1 invariant 0 <= n <= src.Length1 invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j]) invariant forall j :: 0 <= j < n ==> dst[m,j] == old(src[m,j]) { dst[m,n] := src[m,n]; n := n + 1; } m := m + 1; } } // Original davinci-003 completion: // method CopyMatrix(src: array2, dst: array2) // requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 // modifies dst // ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) // { // var m := 0; // while m != src.Length0 // { // var n := 0; // while n != src.Length1 // { // dst[m,n] := src[m,n]; // n := n + 1; // // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> dst[i,j] == old(src[i,j]) // } // m := m + 1; // } // } // Fine_tuned davinci-003 completion: // method CopyMatrix1(src: array2, dst: array2) // requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 // modifies dst // ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) // var m := 0; // while m != src.Length0 // invariant 0 <= m <= src.Length0 // invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) // { // var n := 0; // while n != src.Length1 // invariant 0 <= n <= src.Length1 // { // dst[m,n] := src[m,n]; n := n + 1; // } // m := m + 1; // } method DoubleArray(src: array<int>, dst: array<int>) requires src.Length == dst.Length modifies dst ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) { var n := 0; while n != src.Length invariant 0 <= n <= src.Length invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i]) invariant forall i :: n <= i < src.Length ==> src[i] == old(src[i]) { dst[n] := 2 * src[n]; n := n + 1; } } // Original davinci-003 completion: // method DoubleArray(src: array<int>, dst: array<int>) // requires src.Length == dst.Length // modifies dst // ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) // { // var n := 0; // var i : int := 0; // while n != src.Length // { // dst[n] := 2 * src[n]; // n := n + 1; // i := i + 1; // } // assert i == src.Length; // } // Fine_tuned davinci-003 completion: // method DoubleArray1(src: array<int>, dst: array<int>) // requires src.Length == dst.Length // modifies dst // ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) // { // var n := 0; // while n != src.Length // invariant 0 <= n <= src.Length // invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i]) // { // dst[n] := 2 * src[n]; n := n + 1; // } // } method RotateLeft(a: array) requires a.Length > 0 modifies a ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) ensures a[a.Length -1] == old(a[0]) { var n := 0; while n != a.Length - 1 invariant 0 <= n <= a.Length - 1 invariant forall i :: 0 <= i < n ==> a[i] == old(a[i+1]) invariant a[n] == old(a[0]) invariant forall i :: n < i <= a.Length-1 ==> a[i] == old(a[i]) { a[n], a[n+1] := a[n+1], a[n]; n := n + 1; } } // Original davinci-003 completion: // method RotateLeft(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) // ensures a[a.Length -1] == old(a[0]) // { // var n := 0; // // loop invariant: forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)]) // while n != a.Length - 1 // { // a[n], a[n+1] := a[n+1], a[n]; // n := n + 1; // } // } // Fine_tuned davinci-003 completion: // method RotateLeft1(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) // ensures a[a.Length -1] == old(a[0]) // { // var n := 0; // while n != a.Length - 1 // invariant 0 <= n <= a.Length - 1 // invariant forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)]) // invariant forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) // { // a[n], a[n+1] := a[n+1], a[n]; // n := n + 1; // } // } method RotateRight(a: array) requires a.Length > 0 modifies a ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) ensures a[0] == old(a[a.Length-1]) { var n := 1; while n != a.Length invariant 1 <= n <= a.Length invariant forall i :: 1 <= i < n ==> a[i] == old(a[i-1]) invariant a[0] == old(a[n-1]) invariant forall i :: n <= i <= a.Length-1 ==> a[i] == old(a[i]) { a[0], a[n] := a[n], a[0]; n := n + 1; } } // Original davinci-003 completion: // method RotateRight(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) // ensures a[0] == old(a[a.Length-1]) // { // var n := 1; // var temp := a[0]; // while n != a.Length // { // a[0] := a[n]; // a[n] := temp; // temp := a[0]; // n := n + 1; // // loop invariant: // // forall k :: 0 <= k < n ==> a[k] == old(a[k+1]) // } // } // Fine_tuned davinci-003 completion: // method RotateRight1(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) // ensures a[0] == old(a[a.Length-1]) // { // var n := 1; // while n != a.Length // invariant 1 <= n <= a.Length // invariant forall i :: 1<= i < n ==> a[i] == old(a[(i-1)]) // invariant forall i :: 1<= i < a.Length ==> a[i] == old(a[i]) // { // a[0], a[n] := a[n], a[0]; n := n + 1; // } // }
function Power(n: nat): nat { if n == 0 then 1 else 2 * Power(n - 1) } method ComputePower(N: int) returns (y: nat) requires N >= 0 ensures y == Power(N) { y := 1; var x := 0; while x != N { x, y := x + 1, y + y; } } // Original davinci-003 completion: // method ComputePower1(N: int) returns (y: nat) requires N >= 0 // ensures y == Power(N) // { // y := 1; // var x := 0; // while x != N // decreases N - x // invariant 0 <= x <= N // invariant y == Power(x) // { // x, y := x + 1, y + y; // } // } // Fine_tuned davinci-003 completion: // method ComputePower1(N: int) returns (y: nat) requires N >= 0 // ensures y == Power(N) // { // y := 1; // var x := 0; // while x != N // decreases N - x // invariant 0 <= x <= N // invariant y == Power(x) // { // x, y := x + 1, y + y; // } // } method Max(a: array<nat>) returns (m: int) ensures forall i :: 0 <= i < a.Length ==> a[i] <= m ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i] { m := 0; var n := 0; while n != a.Length { if m < a[n] { m := a[n]; } n := n + 1; } } // Original davinci-003 completion: // method Max(a: array<nat>) returns (m: int) // requires a.Length > 0 // ensures forall i :: 0 <= i < a.Length ==> a[i] <= m // ensures exists i :: 0 <= i < a.Length && m == a[i] // { // m := a[0]; // var n := 1; // while n != a.Length // { // if m < a[n] { // m := a[n]; // } // n := n + 1; // // Loop invariant: 0 <= n <= a.Length && forall i :: 0 <= i < n ==> a[i] <= m // } // } // Fine_tuned davinci-003 completion: // method Max1(a: array<nat>) returns (m: int) // ensures forall i :: 0 <= i < a.Length ==> a[i] <= m // ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i] // { // m := 0; // var n := 0; // while n != a.Length // invariant 0 <= n <= a.Length // invariant forall i :: 0 <= i < n ==> a[i] <= m // { // if m < a[n] { // m := a[n]; // } // n := n + 1; // } // } method Cube(n: nat) returns (c: nat) ensures c == n * n * n { c := 0; var i := 0; var k := 1; var m := 6; while i != n { c, k, m := c + k, k + m, m + 6; i := i + 1; } } // Original davinci-003 completion: // method Cube(n: nat) returns (c: nat) // ensures c == n * n * n // { // c := 0; // var i := 0; // var k := 1; // var m := 6; // // Loop invariant: c = i^3 // while i != n // { // c, k, m := c + k, k + m, m + 6; // i := i + 1; // } // } // Fine_tuned davinci-003 completion: // method Cube1(n: nat) returns (c: nat) // ensures c == n * n * n // { // c := 0; // var i := 0; // var k := 1; // var m := 6; // while i != n // invariant 0 <= i <= n // invariant c == i * k * m // { // c, k, m := c + k, k + m, m + 6; // i := i + 1; // } // } method IncrementMatrix(a: array2<int>) modifies a ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 { var m := 0; while m != a.Length0 { var n := 0; while n != a.Length1 { a[m,n] := a[m,n] + 1; n := n + 1; } m := m + 1; } } // Original davinci-003 completion: // method IncrementMatrix(a: array2<int>) // modifies a // ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // var m := 0; // while m != a.Length0 // { // var n := 0; // while n != a.Length1 // { // // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> a[i,j] == old(a[i,j]) + 1 // a[m,n] := a[m,n] + 1; // n := n + 1; // } // m := m + 1; // } // } // Fine_tuned davinci-003 completion: // method IncrementMatrix1(a: array2<int>) // modifies a // ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // var m := 0; // while m != a.Length0 // invariant 0 <= m <= a.Length0 && 0 <= j < a.Length1 <= a.Length2 // invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // var n := 0; // while n != a.Length1 // invariant 0 <= n <= a.Length2 // invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 // { // a[m,n] := a[m,n] + 1; // n := n + 1; // } // m := m + 1; // } // } method CopyMatrix(src: array2, dst: array2) requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 modifies dst ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) { var m := 0; while m != src.Length0 { var n := 0; while n != src.Length1 { dst[m,n] := src[m,n]; n := n + 1; } m := m + 1; } } // Original davinci-003 completion: // method CopyMatrix(src: array2, dst: array2) // requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 // modifies dst // ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) // { // var m := 0; // while m != src.Length0 // { // var n := 0; // while n != src.Length1 // { // dst[m,n] := src[m,n]; // n := n + 1; // // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> dst[i,j] == old(src[i,j]) // } // m := m + 1; // } // } // Fine_tuned davinci-003 completion: // method CopyMatrix1(src: array2, dst: array2) // requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 // modifies dst // ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) // var m := 0; // while m != src.Length0 // invariant 0 <= m <= src.Length0 // invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) // { // var n := 0; // while n != src.Length1 // invariant 0 <= n <= src.Length1 // { // dst[m,n] := src[m,n]; n := n + 1; // } // m := m + 1; // } method DoubleArray(src: array<int>, dst: array<int>) requires src.Length == dst.Length modifies dst ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) { var n := 0; while n != src.Length { dst[n] := 2 * src[n]; n := n + 1; } } // Original davinci-003 completion: // method DoubleArray(src: array<int>, dst: array<int>) // requires src.Length == dst.Length // modifies dst // ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) // { // var n := 0; // var i : int := 0; // while n != src.Length // { // dst[n] := 2 * src[n]; // n := n + 1; // i := i + 1; // } // assert i == src.Length; // } // Fine_tuned davinci-003 completion: // method DoubleArray1(src: array<int>, dst: array<int>) // requires src.Length == dst.Length // modifies dst // ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) // { // var n := 0; // while n != src.Length // invariant 0 <= n <= src.Length // invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i]) // { // dst[n] := 2 * src[n]; n := n + 1; // } // } method RotateLeft(a: array) requires a.Length > 0 modifies a ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) ensures a[a.Length -1] == old(a[0]) { var n := 0; while n != a.Length - 1 { a[n], a[n+1] := a[n+1], a[n]; n := n + 1; } } // Original davinci-003 completion: // method RotateLeft(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) // ensures a[a.Length -1] == old(a[0]) // { // var n := 0; // // loop invariant: forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)]) // while n != a.Length - 1 // { // a[n], a[n+1] := a[n+1], a[n]; // n := n + 1; // } // } // Fine_tuned davinci-003 completion: // method RotateLeft1(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) // ensures a[a.Length -1] == old(a[0]) // { // var n := 0; // while n != a.Length - 1 // invariant 0 <= n <= a.Length - 1 // invariant forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)]) // invariant forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) // { // a[n], a[n+1] := a[n+1], a[n]; // n := n + 1; // } // } method RotateRight(a: array) requires a.Length > 0 modifies a ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) ensures a[0] == old(a[a.Length-1]) { var n := 1; while n != a.Length { a[0], a[n] := a[n], a[0]; n := n + 1; } } // Original davinci-003 completion: // method RotateRight(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) // ensures a[0] == old(a[a.Length-1]) // { // var n := 1; // var temp := a[0]; // while n != a.Length // { // a[0] := a[n]; // a[n] := temp; // temp := a[0]; // n := n + 1; // // loop invariant: // // forall k :: 0 <= k < n ==> a[k] == old(a[k+1]) // } // } // Fine_tuned davinci-003 completion: // method RotateRight1(a: array) // requires a.Length > 0 // modifies a // ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) // ensures a[0] == old(a[a.Length-1]) // { // var n := 1; // while n != a.Length // invariant 1 <= n <= a.Length // invariant forall i :: 1<= i < n ==> a[i] == old(a[(i-1)]) // invariant forall i :: 1<= i < a.Length ==> a[i] == old(a[i]) // { // a[0], a[n] := a[n], a[0]; n := n + 1; // } // }
147
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_ComputePower.dfy
function Power(n: nat): nat { if n == 0 then 1 else 2 * Power(n - 1) } method ComputePower(N: int) returns (y: nat) requires N >= 0 ensures y == Power(N) { y := 1; var x := 0; while x != N invariant 0 <= x <= N invariant y == Power(x) decreases N - x { x, y := x + 1, y + y; } }
function Power(n: nat): nat { if n == 0 then 1 else 2 * Power(n - 1) } method ComputePower(N: int) returns (y: nat) requires N >= 0 ensures y == Power(N) { y := 1; var x := 0; while x != N { x, y := x + 1, y + y; } }
148
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_CopyMatrix.dfy
method CopyMatrix(src: array2, dst: array2) requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 modifies dst ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) { var m := 0; while m != src.Length0 invariant 0 <= m <= src.Length0 invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j]) { var n := 0; while n != src.Length1 invariant 0 <= n <= src.Length1 invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j]) invariant forall j :: 0 <= j < n ==> dst[m,j] == old(src[m,j]) { dst[m,n] := src[m,n]; n := n + 1; } m := m + 1; } }
method CopyMatrix(src: array2, dst: array2) requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1 modifies dst ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) { var m := 0; while m != src.Length0 { var n := 0; while n != src.Length1 { dst[m,n] := src[m,n]; n := n + 1; } m := m + 1; } }
149
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_Cube.dfy
method Cube(n: nat) returns (c: nat) ensures c == n * n * n { c := 0; var i := 0; var k := 1; var m := 6; while i != n invariant 0 <= i <= n invariant c == i * i * i invariant k == 3*i*i + 3*i + 1 invariant m == 6 * i + 6 { c, k, m := c + k, k + m, m + 6; i := i + 1; } }
method Cube(n: nat) returns (c: nat) ensures c == n * n * n { c := 0; var i := 0; var k := 1; var m := 6; while i != n { c, k, m := c + k, k + m, m + 6; i := i + 1; } }
150
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_DoubleArray.dfy
method DoubleArray(src: array<int>, dst: array<int>) requires src.Length == dst.Length modifies dst ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) { var n := 0; while n != src.Length invariant 0 <= n <= src.Length invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i]) invariant forall i :: n <= i < src.Length ==> src[i] == old(src[i]) { dst[n] := 2 * src[n]; n := n + 1; } }
method DoubleArray(src: array<int>, dst: array<int>) requires src.Length == dst.Length modifies dst ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i]) { var n := 0; while n != src.Length { dst[n] := 2 * src[n]; n := n + 1; } }
151
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_IncrementMatrix.dfy
method IncrementMatrix(a: array2<int>) modifies a ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 { var m := 0; while m != a.Length0 invariant 0 <= m <= a.Length0 invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 invariant forall i, j :: m <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) { var n := 0; while n != a.Length1 invariant 0 <= n <= a.Length1 invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 invariant forall i, j :: m < i < a.Length0 && 0 <= j < a.Length1==> a[i,j] == old(a[i,j]) invariant forall j :: 0 <= j < n ==> a[m,j] == old(a[m,j])+1 invariant forall j :: n <= j < a.Length1 ==> a[m,j] == old(a[m,j]) { a[m,n] := a[m,n] + 1; n := n + 1; } m := m + 1; } }
method IncrementMatrix(a: array2<int>) modifies a ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 { var m := 0; while m != a.Length0 { var n := 0; while n != a.Length1 { a[m,n] := a[m,n] + 1; n := n + 1; } m := m + 1; } }
152
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_RotateRight.dfy
method RotateRight(a: array) requires a.Length > 0 modifies a ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) ensures a[0] == old(a[a.Length-1]) { var n := 1; while n != a.Length invariant 1 <= n <= a.Length invariant forall i :: 1 <= i < n ==> a[i] == old(a[i-1]) invariant a[0] == old(a[n-1]) invariant forall i :: n <= i <= a.Length-1 ==> a[i] == old(a[i]) { a[0], a[n] := a[n], a[0]; n := n + 1; } }
method RotateRight(a: array) requires a.Length > 0 modifies a ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) ensures a[0] == old(a[a.Length-1]) { var n := 1; while n != a.Length { a[0], a[n] := a[n], a[0]; n := n + 1; } }
153
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_28.dfy
method main(x: int, y: int) returns (x_out: int, y_out: int, n: int) requires x >= 0 requires y >= 0 requires x == y ensures y_out == n { x_out := x; y_out := y; n := 0; while (x_out != n) invariant x_out >= 0 invariant x_out == y_out { x_out := x_out - 1; y_out := y_out - 1; } }
method main(x: int, y: int) returns (x_out: int, y_out: int, n: int) requires x >= 0 requires y >= 0 requires x == y ensures y_out == n { x_out := x; y_out := y; n := 0; while (x_out != n) { x_out := x_out - 1; y_out := y_out - 1; } }
154
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_37.dfy
method main(n: int) returns(x: int, m: int) requires n > 0 ensures (n <= 0) || (0 <= m && m < n) { x := 0; m := 0; while(x < n) invariant 0 <= x <= n invariant 0 <= m < n { if(*) { m := x; } else{} x := x + 1; } }
method main(n: int) returns(x: int, m: int) requires n > 0 ensures (n <= 0) || (0 <= m && m < n) { x := 0; m := 0; while(x < n) { if(*) { m := x; } else{} x := x + 1; } }
155
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_38.dfy
method main(n : int) returns (i: int, x: int, y:int) requires n >= 0 ensures (i % 2 != 0) || (x == 2 * y) { i := 0; x := 0; y := 0; while (i < n) invariant 0 <= i <= n invariant x == i invariant y == i / 2 { i := i + 1; x := x + 1; if (i % 2 == 0) { y := y + 1; } else {} } }
method main(n : int) returns (i: int, x: int, y:int) requires n >= 0 ensures (i % 2 != 0) || (x == 2 * y) { i := 0; x := 0; y := 0; while (i < n) { i := i + 1; x := x + 1; if (i % 2 == 0) { y := y + 1; } else {} } }
156
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_41.dfy
method main(n: int, k: int) returns (i :int, j: int) requires n >= 0 requires k == 1 || k >= 0 ensures k + i + j >= 2 * n { i := 0; j := 0; while(i < n) invariant 0 <= i <= n invariant j == i * (i + 1) / 2 { i := i + 1; j := j + i; } }
method main(n: int, k: int) returns (i :int, j: int) requires n >= 0 requires k == 1 || k >= 0 ensures k + i + j >= 2 * n { i := 0; j := 0; while(i < n) { i := i + 1; j := j + i; } }
157
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_BinarySearch.dfy
method BinarySearch(a: array<int>, key: int) returns (n: int) requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures 0 <= n <= a.Length ensures forall i :: 0 <= i < n ==> a[i] < key ensures forall i :: n <= i < a.Length ==> key <= a[i] { var lo, hi := 0, a.Length; while lo < hi invariant 0 <= lo <= hi <= a.Length invariant forall i :: 0 <= i < lo ==> a[i] < key invariant forall i :: hi <= i < a.Length ==> key <= a[i] { var mid := (lo + hi) / 2; if a[mid] < key { lo := mid + 1; } else { hi := mid; } } n := lo; }
method BinarySearch(a: array<int>, key: int) returns (n: int) requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures 0 <= n <= a.Length ensures forall i :: 0 <= i < n ==> a[i] < key ensures forall i :: n <= i < a.Length ==> key <= a[i] { var lo, hi := 0, a.Length; while lo < hi { var mid := (lo + hi) / 2; if a[mid] < key { lo := mid + 1; } else { hi := mid; } } n := lo; }
158
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_SumArray.dfy
function Sum(arr: array<int>, len: int): int reads arr requires arr.Length > 0 && 0 <= len <= arr.Length { if len == 0 then 0 else arr[len-1] + Sum(arr, len-1) } method SumArray(arr: array<int>) returns (sum: int) requires arr.Length > 0 ensures sum == Sum(arr, arr.Length) { sum := 0; var i := 0; while i < arr.Length invariant 0 <= i <= arr.Length invariant sum == Sum(arr, i) { sum := sum + arr[i]; i := i + 1; } }
function Sum(arr: array<int>, len: int): int reads arr requires arr.Length > 0 && 0 <= len <= arr.Length { if len == 0 then 0 else arr[len-1] + Sum(arr, len-1) } method SumArray(arr: array<int>) returns (sum: int) requires arr.Length > 0 ensures sum == Sum(arr, arr.Length) { sum := 0; var i := 0; while i < arr.Length { sum := sum + arr[i]; i := i + 1; } }
159
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_06_n.dfy
method Main() returns (x: int, y: int) ensures x == y; { x := 0; y := 0; var w := 1; var z := 0; var turn := 0; while(x != y) invariant x == y ==> !(0 <= -z*2/2 && 1 <= -(w-1)*2/2) invariant !((x != y && x - y <= -1) || (x - y >= 1 && -z*2/2 <= 0 && (w-1)*2/2 <= 1)) invariant !(w*2/2 <= 0 && ((x != y && (x - y <= -1 || x - y >= 1)) || 1 <= z*2/2)) { if(turn == 0){ turn := 1; } if(turn == 1){ if(w % 2 == 1){ x := x + 1; } if(z % 2 == 0){ y := y + 1; } turn := 1; } else{ if(turn == 2){ z := z + y; w := z + 1; turn := 0; } } } }
method Main() returns (x: int, y: int) ensures x == y; { x := 0; y := 0; var w := 1; var z := 0; var turn := 0; while(x != y) { if(turn == 0){ turn := 1; } if(turn == 1){ if(w % 2 == 1){ x := x + 1; } if(z % 2 == 0){ y := y + 1; } turn := 1; } else{ if(turn == 2){ z := z + y; w := z + 1; turn := 0; } } } }
160
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_07.dfy
method main(n: int) returns (a: int, b: int) requires n >= 0 ensures a + b == 3 * n { var i: int := 0; a := 0; b := 0; while(i < n) invariant 0 <= i <= n invariant a + b == 3 * i { if(*) { a := a + 1; b := b + 2; } else { a := a + 2; b := b + 1; } i := i + 1; } }
method main(n: int) returns (a: int, b: int) requires n >= 0 ensures a + b == 3 * n { var i: int := 0; a := 0; b := 0; while(i < n) { if(*) { a := a + 1; b := b + 2; } else { a := a + 2; b := b + 1; } i := i + 1; } }
161
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_11.dfy
method main(x :int) returns (j :int, i :int) requires x > 0 ensures j == 2 * x { i := 0; j := 0; while i < x invariant 0 <= i <= x invariant j == 2 * i { j := j + 2; i := i + 1; } }
method main(x :int) returns (j :int, i :int) requires x > 0 ensures j == 2 * x { i := 0; j := 0; while i < x { j := j + 2; i := i + 1; } }
162
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_normal_data_completion_MaxPerdV2.dfy
function contains(v: int, a: array<int>, n: int): bool reads a requires n <= a.Length { exists j :: 0 <= j < n && a[j] == v } function upper_bound(v: int, a: array<int>, n: int): bool reads a requires n <= a.Length { forall j :: 0 <= j < n ==> a[j] <= v } function is_max(m: int, a: array<int>, n: int): bool reads a requires n <= a.Length { contains(m, a, n) && upper_bound(m, a, n) } method max(a: array<int>, n: int) returns (max: int) requires 0 < n <= a.Length; ensures is_max(max, a, n); { var i: int := 1; max := a[0]; while i < n invariant i <= n; invariant is_max (max, a, i); { if a[i] > max { max := a[i]; } i := i + 1; } }
function contains(v: int, a: array<int>, n: int): bool reads a requires n <= a.Length { exists j :: 0 <= j < n && a[j] == v } function upper_bound(v: int, a: array<int>, n: int): bool reads a requires n <= a.Length { forall j :: 0 <= j < n ==> a[j] <= v } function is_max(m: int, a: array<int>, n: int): bool reads a requires n <= a.Length { contains(m, a, n) && upper_bound(m, a, n) } method max(a: array<int>, n: int) returns (max: int) requires 0 < n <= a.Length; ensures is_max(max, a, n); { var i: int := 1; max := a[0]; while i < n { if a[i] > max { max := a[i]; } i := i + 1; } }
163
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_15.dfy
method main(n: int, k: int) returns (k_out: int) requires n > 0; requires k > n; ensures k_out >= 0; { k_out := k; var j: int := 0; while(j < n) invariant 0 <= j <= n; invariant k_out == k - j; { j := j + 1; k_out := k_out - 1; } }
method main(n: int, k: int) returns (k_out: int) requires n > 0; requires k > n; ensures k_out >= 0; { k_out := k; var j: int := 0; while(j < n) { j := j + 1; k_out := k_out - 1; } }
164
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_ComputePower.dfy
function Power(n: nat): nat { if n == 0 then 1 else 2 * Power(n - 1) } method ComputePower(n: nat) returns (p: nat) ensures p == Power(n) { p := 1; var i := 0; while i != n invariant 0 <= i <= n && p == Power(i) { i := i + 1; p := p * 2; } }
function Power(n: nat): nat { if n == 0 then 1 else 2 * Power(n - 1) } method ComputePower(n: nat) returns (p: nat) ensures p == Power(n) { p := 1; var i := 0; while i != n { i := i + 1; p := p * 2; } }
165
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Count.dfy
function has_count(v: int, a: array<int>, n: int): int reads a // This allows the function to read from array 'a' requires n >= 0 && n <= a.Length { if n == 0 then 0 else (if a[n-1] == v then has_count(v, a, n-1) + 1 else has_count(v, a, n-1)) } method count (v: int, a: array<int>, n: int) returns (r: int) requires n >= 0 && n <= a.Length; ensures has_count(v, a, n) == r; { var i: int; i := 0; r := 0; while (i < n) invariant 0 <= i <= n invariant r == has_count(v, a, i) { if (a[i] == v) { r := r + 1; } i := i + 1; } return r; }
function has_count(v: int, a: array<int>, n: int): int reads a // This allows the function to read from array 'a' requires n >= 0 && n <= a.Length { if n == 0 then 0 else (if a[n-1] == v then has_count(v, a, n-1) + 1 else has_count(v, a, n-1)) } method count (v: int, a: array<int>, n: int) returns (r: int) requires n >= 0 && n <= a.Length; ensures has_count(v, a, n) == r; { var i: int; i := 0; r := 0; while (i < n) { if (a[i] == v) { r := r + 1; } i := i + 1; } return r; }
166
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_LinearSearch.dfy
method LinearSearch<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) ensures forall i :: 0 <= i < n ==> !P(a[i]) { n := 0; while n != a.Length invariant 0 <= n <= a.Length invariant forall i :: 0 <= i < n ==> !P(a[i]) { if P(a[n]) { return; } n := n + 1; } }
method LinearSearch<T>(a: array<T>, P: T -> bool) returns (n: int) ensures 0 <= n <= a.Length ensures n == a.Length || P(a[n]) ensures forall i :: 0 <= i < n ==> !P(a[i]) { n := 0; while n != a.Length { if P(a[n]) { return; } n := n + 1; } }
167
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Minimum.dfy
method Minimum(a: array<int>) returns (m: int) requires a.Length > 0 ensures exists i :: 0 <= i < a.Length && m == a[i] ensures forall i :: 0 <= i < a.Length ==> m <= a[i] { var n := 0; m := a[0]; while n != a.Length invariant 0 <= n <= a.Length invariant exists i :: 0 <= i < a.Length && m == a[i] invariant forall i :: 0 <= i < n ==> m <= a[i] { if a[n] < m { m := a[n]; } n := n + 1; } }
method Minimum(a: array<int>) returns (m: int) requires a.Length > 0 ensures exists i :: 0 <= i < a.Length && m == a[i] ensures forall i :: 0 <= i < a.Length ==> m <= a[i] { var n := 0; m := a[0]; while n != a.Length { if a[n] < m { m := a[n]; } n := n + 1; } }
168
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Mult.dfy
method mult(a:int, b:int) returns (x:int) requires a >= 0 && b >= 0 ensures x == a * b { x := 0; var y := a; while y > 0 invariant x == (a - y) * b { x := x + b; y := y - 1; } }
method mult(a:int, b:int) returns (x:int) requires a >= 0 && b >= 0 ensures x == a * b { x := 0; var y := a; while y > 0 { x := x + b; y := y - 1; } }
169
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_rand.dfy
method Main(xInit: int, y: int) returns (z: int) requires xInit >= 0 requires y >= 0 ensures z == 0 { var x := xInit; z := x * y; while x > 0 invariant x >= 0 invariant z == x * y decreases x { x := x - 1; z := z - y; } }
method Main(xInit: int, y: int) returns (z: int) requires xInit >= 0 requires y >= 0 ensures z == 0 { var x := xInit; z := x * y; while x > 0 { x := x - 1; z := z - y; } }
170
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Function.dfy
function Average (a: int, b: int): int { (a + b) / 2 } method TripleConditions(x: int) returns (r: int) ensures r == 3 * x { r := 3 * x; assert r == 3 * x; } method Triple' (x: int) returns (r: int) ensures Average(r, 3 * x) == 3 * x ensures r == 3 * x { r:= 3 * x; } method ProveSpecificationsEquivalent(x: int) { var result1 := TripleConditions(x); var result2 := Triple'(x); assert result1 == result2; }
function Average (a: int, b: int): int { (a + b) / 2 } method TripleConditions(x: int) returns (r: int) ensures r == 3 * x { r := 3 * x; } method Triple' (x: int) returns (r: int) ensures Average(r, 3 * x) == 3 * x ensures r == 3 * x { r:= 3 * x; } method ProveSpecificationsEquivalent(x: int) { var result1 := TripleConditions(x); var result2 := Triple'(x); }
171
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Ghost.dfy
function Average(a: int, b: int): int { (a + b) / 2 } ghost method Triple(x: int) returns (r: int) ensures r == 3 * x { r := Average(2 * x, 4 * x); } method Triple1(x: int) returns (r: int) ensures r == 3 * x { var y := 2 * x; r := x + y; ghost var a, b := DoubleQuadruple(x); assert a <= r <= b || b <= r <= a; } ghost method DoubleQuadruple(x: int) returns (a: int, b: int) ensures a == 2 * x && b == 4 * x { a := 2 * x; b := 2 * a; } function F(): int { 29 } method M() returns (r: int) ensures r == 29 { r := 29; } method Caller() { var a := F(); var b := M(); assert a == 29; assert b == 29; } method MyMethod(x: int) returns (y: int) requires 10 <= x ensures 25 <= y { var a, b; a := x + 3; if x < 20 { b := 32 - x; } else { b := 16; } y := a + b; }
function Average(a: int, b: int): int { (a + b) / 2 } ghost method Triple(x: int) returns (r: int) ensures r == 3 * x { r := Average(2 * x, 4 * x); } method Triple1(x: int) returns (r: int) ensures r == 3 * x { var y := 2 * x; r := x + y; ghost var a, b := DoubleQuadruple(x); } ghost method DoubleQuadruple(x: int) returns (a: int, b: int) ensures a == 2 * x && b == 4 * x { a := 2 * x; b := 2 * a; } function F(): int { 29 } method M() returns (r: int) ensures r == 29 { r := 29; } method Caller() { var a := F(); var b := M(); } method MyMethod(x: int) returns (y: int) requires 10 <= x ensures 25 <= y { var a, b; a := x + 3; if x < 20 { b := 32 - x; } else { b := 16; } y := a + b; }
172
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Index.dfy
method Index(n: int) returns (i: int) requires 1 <= n ensures 0 <= i < n { i := n/2; } method Min(x: int, y: int) returns (m: int) ensures m <= x && m <= y ensures m == x || m == y { if (x >= y) { m := y; } else { m := x; } assert m <= x && m <= y; } method Max(x: int, y: int) returns (m: int) { if (x >= y) { m := x; } else { m := y; } assert m >= x && m >= y; } method MaxSum(x: int, y: int) returns (s: int, m: int) ensures s == x + y ensures m == if x >= y then x else y { s := x + y; if (x >= y) { m := x; } else { m := y; } } method MaxSumCaller() { var x: int := 1928; var y: int := 1; var a, b: int; a, b := MaxSum(x, y); assert a == 1929; assert b == 1928; } method ReconstructFromMaxSum(s: int, m: int) returns (x: int, y: int) requires s <= 2 * m ensures s == (x + y) ensures (m == x || m == y) && x <= m && y <= m { x := m; y := s - m; } method TestMaxSum(x: int, y: int) { var s, m := MaxSum(x, y); var xx, yy := ReconstructFromMaxSum(s, m); assert (xx == x && yy == y) || (xx == y && yy == x); }
method Index(n: int) returns (i: int) requires 1 <= n ensures 0 <= i < n { i := n/2; } method Min(x: int, y: int) returns (m: int) ensures m <= x && m <= y ensures m == x || m == y { if (x >= y) { m := y; } else { m := x; } } method Max(x: int, y: int) returns (m: int) { if (x >= y) { m := x; } else { m := y; } } method MaxSum(x: int, y: int) returns (s: int, m: int) ensures s == x + y ensures m == if x >= y then x else y { s := x + y; if (x >= y) { m := x; } else { m := y; } } method MaxSumCaller() { var x: int := 1928; var y: int := 1; var a, b: int; a, b := MaxSum(x, y); } method ReconstructFromMaxSum(s: int, m: int) returns (x: int, y: int) requires s <= 2 * m ensures s == (x + y) ensures (m == x || m == y) && x <= m && y <= m { x := m; y := s - m; } method TestMaxSum(x: int, y: int) { var s, m := MaxSum(x, y); var xx, yy := ReconstructFromMaxSum(s, m); }
173
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_LoopInvariant.dfy
method UpWhileLess(N: int) returns (i: int) requires 0 <= N ensures i == N { i := 0; while i < N invariant 0 <= i <= N decreases N - i { i := i + 1; } } method UpWhileNotEqual(N: int) returns (i: int) requires 0 <= N ensures i == N { i := 0; while i != N invariant 0 <= i <= N decreases N - i { i := i + 1; } } method DownWhileNotEqual(N: int) returns (i: int) requires 0 <= N ensures i == 0 { i := N; while i != 0 invariant 0 <= i <= N decreases i { i := i - 1; } } method DownWhileGreater(N: int) returns (i: int) requires 0 <= N ensures i == 0 { i := N; while 0 < i invariant 0 <= i <= N decreases i { i := i - 1; } } method Quotient() { var x, y := 0, 191; while 7 <= y invariant 0 <= y && 7 * x + y == 191 { y := y - 7; x := x + 1; } assert x == 191 / 7 && y == 191 % 7; } method Quotient1() { var x, y := 0, 191; while 7 <= y invariant 0 <= y && 7 * x + y == 191 { x, y := 27, 2; } assert x == 191 / 7 && y == 191 % 7; }
method UpWhileLess(N: int) returns (i: int) requires 0 <= N ensures i == N { i := 0; while i < N { i := i + 1; } } method UpWhileNotEqual(N: int) returns (i: int) requires 0 <= N ensures i == N { i := 0; while i != N { i := i + 1; } } method DownWhileNotEqual(N: int) returns (i: int) requires 0 <= N ensures i == 0 { i := N; while i != 0 { i := i - 1; } } method DownWhileGreater(N: int) returns (i: int) requires 0 <= N ensures i == 0 { i := N; while 0 < i { i := i - 1; } } method Quotient() { var x, y := 0, 191; while 7 <= y { y := y - 7; x := x + 1; } } method Quotient1() { var x, y := 0, 191; while 7 <= y { x, y := 27, 2; } }
174
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Triple.dfy
method Triple(x: int) returns (r: int) { var y := 2 * x; r := x + y; assert r == 3 * x; } method TripleIf(x: int) returns (r: int) { if (x == 0) { r := 0; } else { var y := 2 * x; r := x + y; } assert r == 3 * x; } method TripleOver(x: int) returns (r: int) { if { case x < 18 => var a, b := 2 * x, 4 * x; r := (a + b) / 2; case 0 <= x => var y:= 2 * x; r := x + y; } assert r == 3 * x; } method TripleConditions(x: int) returns (r: int) requires x % 2 == 0 ensures r == 3 * x { var y := x / 2; r := 6 * y; assert r == 3 * x; } method Caller() { var t := TripleConditions(18); assert t < 100; }
method Triple(x: int) returns (r: int) { var y := 2 * x; r := x + y; } method TripleIf(x: int) returns (r: int) { if (x == 0) { r := 0; } else { var y := 2 * x; r := x + y; } } method TripleOver(x: int) returns (r: int) { if { case x < 18 => var a, b := 2 * x, 4 * x; r := (a + b) / 2; case 0 <= x => var y:= 2 * x; r := x + y; } } method TripleConditions(x: int) returns (r: int) requires x % 2 == 0 ensures r == 3 * x { var y := x / 2; r := 6 * y; } method Caller() { var t := TripleConditions(18); }
175
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_solved_1_select.dfy
method SelectionSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { var n := 0; while n != a.Length invariant 0 <= n <= a.Length invariant forall i,j :: 0 <= i < j < a.Length && j < n ==> a[i] <= a[j] invariant forall i :: 0 <= i < n ==> forall j :: n <= j < a.Length ==> a[i] <= a[j] invariant multiset(a[..]) == old(multiset(a[..])) { var mindex, m := n, n; while m != a.Length invariant n <= mindex < a.Length invariant n <= m <= a.Length invariant forall i :: n <= i < m ==> a[mindex] <= a[i] invariant multiset(a[..]) == old(multiset(a[..])) { if a[m] < a[mindex] { mindex := m; } m := m + 1; } if a[mindex] < a[n] { a[mindex], a[n] := a[n], a[mindex]; } n := n + 1; } }
method SelectionSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { var n := 0; while n != a.Length { var mindex, m := n, n; while m != a.Length { if a[m] < a[mindex] { mindex := m; } m := m + 1; } if a[mindex] < a[n] { a[mindex], a[n] := a[n], a[mindex]; } n := n + 1; } }
176
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_01.dfy
method main() returns (t1: int, t2: int, x: int, y: int) ensures y >= 1 { x := 1; y := 1; t1 := 0; t2 := 0; while(x <= 100000) invariant x == y; { t1 := x; t2 := y; x := t1 + t2; y := t1 + t2; } }
method main() returns (t1: int, t2: int, x: int, y: int) ensures y >= 1 { x := 1; y := 1; t1 := 0; t2 := 0; while(x <= 100000) { t1 := x; t2 := y; x := t1 + t2; y := t1 + t2; } }
177
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_06_n.dfy
// MODULE main // int x; // int y; // int w; // int z; // int turn; // assume(x == 0); // assume(y == 0); // assume(z == 0); // assume(w == 1); // assume(turn == 0); // while(*){ // if(turn == 0){ // if(*){ // turn = 1; // } // else{ // turn = 2; // } // } // else{ // skip; // } // if(turn == 1){ // if(w % 2 == 1){ // x = x + 1; // } // else{ // skip; // } // if(z % 2 == 0){ // y = y + 1; // } // else{ // skip; // } // if(*){ // turn = 1; // } // else{ // turn = 2; // } // } // else{ // if(turn == 2){ // z = z + y; // w = z + 1; // turn = 0; // } // else{ // skip; // } // } // } // assert(x == y); // END MODULE // (let ((.def_28 (= x y))) (let ((.def_1294 (<= (+ x (* (- 1) y)) (- 1)))) (let ((.def_1298 (<= 1 (+ x (* (- 1) y))))) (let ((.def_3281 (and (not (<= 0 (+ z (* 2 (to_int (* (/ 1 2) (to_real (* (- 1) z)))))))) (not (<= 1 (+ w (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) w) 1))))))))))) (not (and (and (not (and (not .def_1298) (and (not .def_1294) .def_3281))) (not (and .def_28 .def_3281))) (not (and (not (<= (to_real (+ w (* (- 2) (to_int (* (/ 1 2) (to_real (* 1 w))))))) (to_real 0))) (and (not (and (not .def_28) (or .def_1294 .def_1298))) (not (<= (to_real 1) (to_real (+ z (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) z) 1)))))))))))))))))) method Main() returns (x: int, y: int) ensures x == y; { x := 0; y := 0; var w := 1; var z := 0; var turn := 0; while(x != y) invariant x == y ==> !(0 <= -z*2/2 && 1 <= -(w-1)*2/2) invariant !((x != y && x - y <= -1) || (x - y >= 1 && -z*2/2 <= 0 && (w-1)*2/2 <= 1)) invariant !(w*2/2 <= 0 && ((x != y && (x - y <= -1 || x - y >= 1)) || 1 <= z*2/2)) { if(turn == 0){ turn := 1; } if(turn == 1){ if(w % 2 == 1){ x := x + 1; } if(z % 2 == 0){ y := y + 1; } turn := 1; } else{ if(turn == 2){ z := z + y; w := z + 1; turn := 0; } } } }
// MODULE main // int x; // int y; // int w; // int z; // int turn; // assume(x == 0); // assume(y == 0); // assume(z == 0); // assume(w == 1); // assume(turn == 0); // while(*){ // if(turn == 0){ // if(*){ // turn = 1; // } // else{ // turn = 2; // } // } // else{ // skip; // } // if(turn == 1){ // if(w % 2 == 1){ // x = x + 1; // } // else{ // skip; // } // if(z % 2 == 0){ // y = y + 1; // } // else{ // skip; // } // if(*){ // turn = 1; // } // else{ // turn = 2; // } // } // else{ // if(turn == 2){ // z = z + y; // w = z + 1; // turn = 0; // } // else{ // skip; // } // } // } // assert(x == y); // END MODULE // (let ((.def_28 (= x y))) (let ((.def_1294 (<= (+ x (* (- 1) y)) (- 1)))) (let ((.def_1298 (<= 1 (+ x (* (- 1) y))))) (let ((.def_3281 (and (not (<= 0 (+ z (* 2 (to_int (* (/ 1 2) (to_real (* (- 1) z)))))))) (not (<= 1 (+ w (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) w) 1))))))))))) (not (and (and (not (and (not .def_1298) (and (not .def_1294) .def_3281))) (not (and .def_28 .def_3281))) (not (and (not (<= (to_real (+ w (* (- 2) (to_int (* (/ 1 2) (to_real (* 1 w))))))) (to_real 0))) (and (not (and (not .def_28) (or .def_1294 .def_1298))) (not (<= (to_real 1) (to_real (+ z (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) z) 1)))))))))))))))))) method Main() returns (x: int, y: int) ensures x == y; { x := 0; y := 0; var w := 1; var z := 0; var turn := 0; while(x != y) { if(turn == 0){ turn := 1; } if(turn == 1){ if(w % 2 == 1){ x := x + 1; } if(z % 2 == 0){ y := y + 1; } turn := 1; } else{ if(turn == 2){ z := z + y; w := z + 1; turn := 0; } } } }
178
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_07.dfy
// MODULE main // int i; // int n; // int a; // int b; // assume(i == 0); // assume(a == 0); // assume(b == 0); // assume(n >= 0); // while(i < n){ // if(*) { // a = a+1; // b = b+2; // } // else { // a = a+2; // b = b+1; // } // i = i+1; // } // assert(a + b == 3 * n); // END MODULE // (let ((.def_201 (<= (+ (* 3 n) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (let ((.def_392 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (not (or (<= 1 (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b)))) (and (or .def_201 .def_392) (or .def_392 (and .def_201 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) 0)))))))) method main(n: int) returns (a: int, b: int) requires n >= 0 ensures a + b == 3 * n { var i: int := 0; a := 0; b := 0; while(i < n) invariant 0 <= i <= n invariant a + b == 3 * i { if(*) { a := a + 1; b := b + 2; } else { a := a + 2; b := b + 1; } i := i + 1; } }
// MODULE main // int i; // int n; // int a; // int b; // assume(i == 0); // assume(a == 0); // assume(b == 0); // assume(n >= 0); // while(i < n){ // if(*) { // a = a+1; // b = b+2; // } // else { // a = a+2; // b = b+1; // } // i = i+1; // } // assert(a + b == 3 * n); // END MODULE // (let ((.def_201 (<= (+ (* 3 n) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (let ((.def_392 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (not (or (<= 1 (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b)))) (and (or .def_201 .def_392) (or .def_392 (and .def_201 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) 0)))))))) method main(n: int) returns (a: int, b: int) requires n >= 0 ensures a + b == 3 * n { var i: int := 0; a := 0; b := 0; while(i < n) { if(*) { a := a + 1; b := b + 2; } else { a := a + 2; b := b + 1; } i := i + 1; } }
179
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_11.dfy
method main(x :int) returns (j :int, i :int) requires x > 0 ensures j == 2 * x { i := 0; j := 0; while i < x invariant 0 <= i <= x invariant j == 2 * i { j := j + 2; i := i + 1; } } // MODULE main // int i; // int j; // int x; // assume(j == 0); // assume(x > 0); // assume(i == 0); // while(i < x){ // j = j + 2; // i = i + 1; // } // assert(j == 2*x); // END MODULE // (and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) (and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j)))))) // (and // (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) // (not (<= 1 (+ j (* (- 2) x)))) // (not (<= 1 (+ (* 2 i) (* (- 1) j)))) // ( // and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) ( // and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j))))))
method main(x :int) returns (j :int, i :int) requires x > 0 ensures j == 2 * x { i := 0; j := 0; while i < x { j := j + 2; i := i + 1; } } // MODULE main // int i; // int j; // int x; // assume(j == 0); // assume(x > 0); // assume(i == 0); // while(i < x){ // j = j + 2; // i = i + 1; // } // assert(j == 2*x); // END MODULE // (and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) (and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j)))))) // (and // (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) // (not (<= 1 (+ j (* (- 2) x)))) // (not (<= 1 (+ (* 2 i) (* (- 1) j)))) // ( // and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) ( // and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j))))))
180
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_15.dfy
method main(n: int, k: int) returns (k_out: int) requires n > 0; requires k > n; ensures k_out >= 0; { k_out := k; var j: int := 0; while(j < n) invariant 0 <= j <= n; invariant j + k_out == k; { j := j + 1; k_out := k_out - 1; } } // C code: // MODULE main // int i; // int n; // int j; // int k; // assume(n > 0); // assume(k > n); // assume(j == 0); // while(j < n){ // j = j + 1; // k = k - 1; // } // assert(k >= 0); // END MODULE // Invariant // ( // not (or (<= 1 (+ n (+ (* (- 1) j) (* (- 1) k)))) ( // and (<= k (- 1)) (<= (+ n (* (- 1) j)) (- 1)))))
method main(n: int, k: int) returns (k_out: int) requires n > 0; requires k > n; ensures k_out >= 0; { k_out := k; var j: int := 0; while(j < n) { j := j + 1; k_out := k_out - 1; } } // C code: // MODULE main // int i; // int n; // int j; // int k; // assume(n > 0); // assume(k > n); // assume(j == 0); // while(j < n){ // j = j + 1; // k = k - 1; // } // assert(k >= 0); // END MODULE // Invariant // ( // not (or (<= 1 (+ n (+ (* (- 1) j) (* (- 1) k)))) ( // and (<= k (- 1)) (<= (+ n (* (- 1) j)) (- 1)))))
181
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_23_x.dfy
method main(n: int) returns (sum: int, i: int) requires n >= 0 { sum := 0; i := 0; while(i < n) invariant sum >= 0 invariant 0 <= i <= n { sum := sum + i; i := i + 1; } } // MODULE main // int i; // int sum; // int n; // assume(sum == 0); // assume(n >= 0); // assume(i == 0); // while(i < n){ // sum = sum + i; // i = i + 1; // } // assert(sum >= 0); // END MODULE
method main(n: int) returns (sum: int, i: int) requires n >= 0 { sum := 0; i := 0; while(i < n) { sum := sum + i; i := i + 1; } } // MODULE main // int i; // int sum; // int n; // assume(sum == 0); // assume(n >= 0); // assume(i == 0); // while(i < n){ // sum = sum + i; // i = i + 1; // } // assert(sum >= 0); // END MODULE
182
Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_Min.dfy
method min(a: array<int>, n : int) returns (min : int) requires 0 < n <= a.Length; ensures (exists i : int :: 0 <= i && i < n && a[i] == min); ensures (forall i : int :: 0 <= i && i < n ==> a[i] >= min); { var i : int; min := a[0]; i := 1; while (i < n) invariant i <= n; invariant (exists j : int :: 0 <= j && j < i && a[j] == min); invariant (forall j : int :: 0 <= j && j < i ==> a[j] >= min); { if (a[i] < min) { min := a[i]; } i := i + 1; } }
method min(a: array<int>, n : int) returns (min : int) requires 0 < n <= a.Length; ensures (exists i : int :: 0 <= i && i < n && a[i] == min); ensures (forall i : int :: 0 <= i && i < n ==> a[i] >= min); { var i : int; min := a[0]; i := 1; while (i < n) { if (a[i] < min) { min := a[i]; } i := i + 1; } }
183
Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_SmallNum.dfy
method add_small_numbers (a: array<int>, n: int, max: int) returns (r: int) requires n > 0; requires n <= a.Length; requires (forall i: int :: 0 <= i && i < n ==> a[i] <= max); ensures r <= max * n; { var i: int; i := 0; r := 0; while (i < n) invariant i <= n; invariant r <= max * i; { r := r + a[i]; i := i + 1; } }
method add_small_numbers (a: array<int>, n: int, max: int) returns (r: int) requires n > 0; requires n <= a.Length; requires (forall i: int :: 0 <= i && i < n ==> a[i] <= max); ensures r <= max * n; { var i: int; i := 0; r := 0; while (i < n) { r := r + a[i]; i := i + 1; } }
184
Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_Square.dfy
method square (n: int) returns (r: int) requires 0 <= n; ensures r == n*n; { var x: int; var i: int; r := 0; i := 0; x := 1; while (i < n) invariant i <= n; invariant r == i*i; invariant x == 2*i + 1; { r := r + x; x := x + 2; i := i + 1; } }
method square (n: int) returns (r: int) requires 0 <= n; ensures r == n*n; { var x: int; var i: int; r := 0; i := 0; x := 1; while (i < n) { r := r + x; x := x + 2; i := i + 1; } }
185
Dafny_Verify_tmp_tmphq7j0row_dataset_detailed_examples_SelectionSort.dfy
// Works by dividing the input list into two parts: sorted and unsorted. At the beginning, // the sorted part is empty and the unsorted part contains all the elements. method SelectionSort(a: array<int>) modifies a // Ensures the final array is sorted in ascending order ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] // Ensures that the final array has the same elements as the initial array ensures multiset(a[..]) == old(multiset(a[..])) { var n := 0; while n != a.Length // Ensures that n is always within the bounds of the array invariant 0 <= n <= a.Length // Guarantees that the portion of the array up to index n is sorted invariant forall i,j :: 0 <= i < j < a.Length && j < n ==> a[i] <= a[j] // Guarantees that all elements before n are less than or equal to elements after and at n invariant forall i :: 0 <= i < n ==> forall j :: n <= j < a.Length ==> a[i] <= a[j] // Ensures that the array still contains the same elements as the initial array invariant multiset(a[..]) == old(multiset(a[..])) { var mindex, m := n, n; while m != a.Length // Ensures that mindex is always within the bounds of the array invariant n <= mindex < a.Length invariant n <= m <= a.Length // Ensures that a[mindex] is the smallest element from a[n] to a[m-1] invariant forall i :: n <= i < m ==> a[mindex] <= a[i] // Ensures that the array still contains the same elements as the initial array invariant multiset(a[..]) == old(multiset(a[..])) { if a[m] < a[mindex] { mindex := m; } m := m + 1; } // Swaps the first element of the unsorted array with the current smallest element // in the unsorted part if it is smaller if a[mindex] < a[n] { a[mindex], a[n] := a[n], a[mindex]; } n := n + 1; } }
// Works by dividing the input list into two parts: sorted and unsorted. At the beginning, // the sorted part is empty and the unsorted part contains all the elements. method SelectionSort(a: array<int>) modifies a // Ensures the final array is sorted in ascending order ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] // Ensures that the final array has the same elements as the initial array ensures multiset(a[..]) == old(multiset(a[..])) { var n := 0; while n != a.Length // Ensures that n is always within the bounds of the array // Guarantees that the portion of the array up to index n is sorted // Guarantees that all elements before n are less than or equal to elements after and at n // Ensures that the array still contains the same elements as the initial array { var mindex, m := n, n; while m != a.Length // Ensures that mindex is always within the bounds of the array // Ensures that a[mindex] is the smallest element from a[n] to a[m-1] // Ensures that the array still contains the same elements as the initial array { if a[m] < a[mindex] { mindex := m; } m := m + 1; } // Swaps the first element of the unsorted array with the current smallest element // in the unsorted part if it is smaller if a[mindex] < a[n] { a[mindex], a[n] := a[n], a[mindex]; } n := n + 1; } }
186
Dafny_Verify_tmp_tmphq7j0row_dataset_error_data_real_error_IsEven_success_1.dfy
function even(n: int): bool requires n >= 0 { if n == 0 then true else !even(n-1) } method is_even(n: int) returns (r: bool) requires n >= 0; ensures r <==> even(n); { var i: int := 0; r := true; while i < n invariant 0 <= i <= n; invariant r <==> even(i); { r := !r; i := i + 1; } }
function even(n: int): bool requires n >= 0 { if n == 0 then true else !even(n-1) } method is_even(n: int) returns (r: bool) requires n >= 0; ensures r <==> even(n); { var i: int := 0; r := true; while i < n { r := !r; i := i + 1; } }
187
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 1_LinearSearch.dfy
// Author of question: Snorri Agnarsson // Permalink of question: https://rise4fun.com/Dafny/0HRr // Author of solution: Alexander Guðmundsson // Permalink of solution: https://rise4fun.com/Dafny/8pxWd // Use the command // dafny LinearSearch-skeleton.dfy // or // compile LinearSearch-skeleton.dfy // to compile the file. // Or use the web page rise4fun.com/dafny. // When you have solved the problem put // the solution on the Dafny web page, // generate a permalink and put it in // this file. method SearchRecursive( a: seq<int>, i: int, j: int, x: int ) returns (k: int) decreases j-i; requires 0 <= i <= j <= |a|; ensures i <= k < j || k == -1; ensures k != -1 ==> a[k] == x; ensures k != -1 ==> forall r | k < r < j :: a[r] != x; ensures k == -1 ==> forall r | i <= r < j :: a[r] != x; { // Put program text here so that Dafny // accepts this function. // In this function loops are not allowed // but recursion should be used, and it // is not allowed to call the function // SearchLoop below. if j == i { k := -1; return; } if a[j-1] == x { k := j-1; return; } else { k := SearchRecursive(a, i, j-1, x); } } method SearchLoop( a: seq<int>, i: int, j: int, x: int ) returns (k: int) requires 0 <= i <= j <= |a|; ensures i <= k < j || k == -1; ensures k != -1 ==> a[k] == x; ensures k != -1 ==> forall r | k < r < j :: a[r] != x; ensures k == -1 ==> forall r | i <= r < j :: a[r] != x; { // Put program text here so that Dafny // accepts this function. // In this function recursion is not allowed // and it is not allowed to call the function // SearchRecursive above. if i == j { return -1; } var t := j; while t > i decreases t; invariant forall p | t <= p < j :: a[p] != x; { if a[t-1] == x { k := t-1; return; } else { t := t - 1; } } k := -1; }
// Author of question: Snorri Agnarsson // Permalink of question: https://rise4fun.com/Dafny/0HRr // Author of solution: Alexander Guðmundsson // Permalink of solution: https://rise4fun.com/Dafny/8pxWd // Use the command // dafny LinearSearch-skeleton.dfy // or // compile LinearSearch-skeleton.dfy // to compile the file. // Or use the web page rise4fun.com/dafny. // When you have solved the problem put // the solution on the Dafny web page, // generate a permalink and put it in // this file. method SearchRecursive( a: seq<int>, i: int, j: int, x: int ) returns (k: int) requires 0 <= i <= j <= |a|; ensures i <= k < j || k == -1; ensures k != -1 ==> a[k] == x; ensures k != -1 ==> forall r | k < r < j :: a[r] != x; ensures k == -1 ==> forall r | i <= r < j :: a[r] != x; { // Put program text here so that Dafny // accepts this function. // In this function loops are not allowed // but recursion should be used, and it // is not allowed to call the function // SearchLoop below. if j == i { k := -1; return; } if a[j-1] == x { k := j-1; return; } else { k := SearchRecursive(a, i, j-1, x); } } method SearchLoop( a: seq<int>, i: int, j: int, x: int ) returns (k: int) requires 0 <= i <= j <= |a|; ensures i <= k < j || k == -1; ensures k != -1 ==> a[k] == x; ensures k != -1 ==> forall r | k < r < j :: a[r] != x; ensures k == -1 ==> forall r | i <= r < j :: a[r] != x; { // Put program text here so that Dafny // accepts this function. // In this function recursion is not allowed // and it is not allowed to call the function // SearchRecursive above. if i == j { return -1; } var t := j; while t > i { if a[t-1] == x { k := t-1; return; } else { t := t - 1; } } k := -1; }
188
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 2_BinarySearchDec.dfy
// Author of question: Snorri Agnarsson // Permalink of question: https://rise4fun.com/Dafny/CGB1z // Authors of solution: Alexander Guðmundsson // Permalink of solution: https://rise4fun.com/Dafny/VnB5 // Use the command // dafny H2-skeleton.dfy // or // compile H2-skeleton.dfy // to compile the file. // Or use the web page rise4fun.com/dafny. // When you have solved the problem put // the solution on the Dafny web page, // generate a permalink and put it in // this file. method SearchRecursive( a: seq<real>, i: int, j: int, x: real ) returns ( k: int ) decreases j-i; requires 0 <= i <= j <= |a|; requires forall p, q :: i <= p < q < j ==> a[p] >= a[q]; ensures i <= k <= j ensures forall r | i <= r < k :: a[r] >= x; ensures forall r | k <= r < j :: a[r] < x; { if i == j { return i; } var m := i + (j-i)/2; if a[m] < x { k := SearchRecursive(a,i,m,x); } else { k := SearchRecursive(a,m+1,j,x); } } method SearchLoop( a: seq<real>, i: int, j: int, x: real ) returns ( k: int ) requires 0 <= i <= j <= |a|; requires forall p, q :: i <= p < q < j ==> a[p] >= a[q]; ensures i <= k <= j; ensures forall r | i <= r < k :: a[r] >= x; ensures forall r | k <= r < j :: a[r] < x; { if i == j { return i; } var p := i; var q := j; while p != q decreases q-p; invariant i <= p <= q <= j; invariant forall r | i <= r < p :: a[r] >= x; invariant forall r | q <= r < j :: a[r] < x; { var m := p + (q-p)/2; if a[m] < x { q := m; } else { p := m+1; } } return p; } // Ef eftirfarandi fall er ekki samþykkt þá eru // föllin ekki að haga sér rétt að mati Dafny. method Test( a: seq<real>, x: real ) requires forall p,q | 0 <= p < q < |a| :: a[p] >= a[q]; { var k1 := SearchLoop(a,0,|a|,x); assert forall r | 0 <= r < k1 :: a[r] >= x; assert forall r | k1 <= r < |a| :: a[r] < x; var k2 := SearchRecursive(a,0,|a|,x); assert forall r | 0 <= r < k2 :: a[r] >= x; assert forall r | k2 <= r < |a| :: a[r] < x; }
// Author of question: Snorri Agnarsson // Permalink of question: https://rise4fun.com/Dafny/CGB1z // Authors of solution: Alexander Guðmundsson // Permalink of solution: https://rise4fun.com/Dafny/VnB5 // Use the command // dafny H2-skeleton.dfy // or // compile H2-skeleton.dfy // to compile the file. // Or use the web page rise4fun.com/dafny. // When you have solved the problem put // the solution on the Dafny web page, // generate a permalink and put it in // this file. method SearchRecursive( a: seq<real>, i: int, j: int, x: real ) returns ( k: int ) requires 0 <= i <= j <= |a|; requires forall p, q :: i <= p < q < j ==> a[p] >= a[q]; ensures i <= k <= j ensures forall r | i <= r < k :: a[r] >= x; ensures forall r | k <= r < j :: a[r] < x; { if i == j { return i; } var m := i + (j-i)/2; if a[m] < x { k := SearchRecursive(a,i,m,x); } else { k := SearchRecursive(a,m+1,j,x); } } method SearchLoop( a: seq<real>, i: int, j: int, x: real ) returns ( k: int ) requires 0 <= i <= j <= |a|; requires forall p, q :: i <= p < q < j ==> a[p] >= a[q]; ensures i <= k <= j; ensures forall r | i <= r < k :: a[r] >= x; ensures forall r | k <= r < j :: a[r] < x; { if i == j { return i; } var p := i; var q := j; while p != q { var m := p + (q-p)/2; if a[m] < x { q := m; } else { p := m+1; } } return p; } // Ef eftirfarandi fall er ekki samþykkt þá eru // föllin ekki að haga sér rétt að mati Dafny. method Test( a: seq<real>, x: real ) requires forall p,q | 0 <= p < q < |a| :: a[p] >= a[q]; { var k1 := SearchLoop(a,0,|a|,x); var k2 := SearchRecursive(a,0,|a|,x); }
189
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 3_InsertionSortMultiset.dfy
// Höfundur spurningar: Snorri Agnarsson, snorri@hi.is // Permalink spurningar: https://rise4fun.com/Dafny/G4sc3 // Höfundur lausnar: Alexander Guðmundsson // Permalink lausnar: https://rise4fun.com/Dafny/nujsu // Insertion sort með hjálp helmingunarleitar. method Search( s: seq<int>, x: int ) returns ( k: int ) // Ekki má breyta forskilyrðum eða eftirskilyrðum fallsins requires forall p,q | 0 <= p < q < |s| :: s[p] <= s[q]; ensures 0 <= k <= |s|; ensures forall i | 0 <= i < k :: s[i] <= x; ensures forall i | k <= i < |s| :: s[i] >= x; ensures forall z | z in s[..k] :: z <= x; ensures forall z | z in s[k..] :: z >= x; ensures s == s[..k]+s[k..]; { // Setjið viðeigandi stofn fallsins hér. var p := 0; var q := |s|; if p == q { return p; } while p != q decreases q-p; invariant 0 <= p <= q <= |s|; invariant forall r | 0 <= r < p :: s[r] <= x; invariant forall r | q <= r < |s| :: s[r] >= x; { var m := p + (q-p)/2; if s[m] == x { return m; } if s[m] < x { p := m+1; } else { q := m; } } return p; } method Sort( m: multiset<int> ) returns ( r: seq<int> ) ensures multiset(r) == m; ensures forall p,q | 0 <= p < q < |r| :: r[p] <= r[q]; { // Setjið viðeigandi frumstillingu á r og rest hér. // r er skilabreyta en rest er ný breyta sem þið búið til. r := []; var rest := m; while rest != multiset{} // Ekki breyta fastayrðingu lykkju decreases rest; invariant m == multiset(r)+rest; invariant forall p,q | 0 <= p < q < |r| :: r[p] <= r[q]; { // Setjið viðeigandi stofn lykkjunnar hér. // Fjarlægið eitt gildi úr rest með // var x :| x in rest; // rest := rest-multiset{x}; // og notið Search til að finna réttan stað // í r til að stinga [x] inn í r. var x :| x in rest; rest := rest - multiset{x}; var k := Search(r, x); r := r[..k] + [x] + r[k..]; } return r; }
// Höfundur spurningar: Snorri Agnarsson, snorri@hi.is // Permalink spurningar: https://rise4fun.com/Dafny/G4sc3 // Höfundur lausnar: Alexander Guðmundsson // Permalink lausnar: https://rise4fun.com/Dafny/nujsu // Insertion sort með hjálp helmingunarleitar. method Search( s: seq<int>, x: int ) returns ( k: int ) // Ekki má breyta forskilyrðum eða eftirskilyrðum fallsins requires forall p,q | 0 <= p < q < |s| :: s[p] <= s[q]; ensures 0 <= k <= |s|; ensures forall i | 0 <= i < k :: s[i] <= x; ensures forall i | k <= i < |s| :: s[i] >= x; ensures forall z | z in s[..k] :: z <= x; ensures forall z | z in s[k..] :: z >= x; ensures s == s[..k]+s[k..]; { // Setjið viðeigandi stofn fallsins hér. var p := 0; var q := |s|; if p == q { return p; } while p != q { var m := p + (q-p)/2; if s[m] == x { return m; } if s[m] < x { p := m+1; } else { q := m; } } return p; } method Sort( m: multiset<int> ) returns ( r: seq<int> ) ensures multiset(r) == m; ensures forall p,q | 0 <= p < q < |r| :: r[p] <= r[q]; { // Setjið viðeigandi frumstillingu á r og rest hér. // r er skilabreyta en rest er ný breyta sem þið búið til. r := []; var rest := m; while rest != multiset{} // Ekki breyta fastayrðingu lykkju { // Setjið viðeigandi stofn lykkjunnar hér. // Fjarlægið eitt gildi úr rest með // var x :| x in rest; // rest := rest-multiset{x}; // og notið Search til að finna réttan stað // í r til að stinga [x] inn í r. var x :| x in rest; rest := rest - multiset{x}; var k := Search(r, x); r := r[..k] + [x] + r[k..]; } return r; }
190
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 3_SelectionSortMultiset.dfy
// Höfundur spurningar: Snorri Agnarsson, snorri@hi.is // Permalink spurningar: https://rise4fun.com/Dafny/dtcnY // Höfundur lausnar: Alexander Guðmundsson // Permalink lausnar: https://rise4fun.com/Dafny/ybUCz /////////////////////////////////////////////////////////////// // Hér byrjar óbreytanlegi hluti skrárinnar. // Fyrir aftan þann hluta er sá hluti sem þið eigið að breyta. /////////////////////////////////////////////////////////////// // Hjálparfall sem finnur minnsta gildi í poka method MinOfMultiset( m: multiset<int> ) returns( min: int ) requires m != multiset{}; ensures min in m; ensures forall z | z in m :: min <= z; { min :| min in m; var done := multiset{min}; var m' := m-done; while m' != multiset{} decreases m'; invariant m == done+m'; invariant min in done; invariant forall z | z in done :: min <= z; { var z :| z in m'; done := done+multiset{z}; m' := m'-multiset{z}; if z < min { min := z; } } } // Ekki má breyta þessu falli. method Test( m: multiset<int> ) { var s := Sort(m); assert multiset(s) == m; assert forall p,q | 0 <= p < q < |s| :: s[p] <= s[q]; } method Main() { var m := multiset{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9}; var s := Sort(m); assert multiset(s) == m; assert forall p,q | 0 <= p < q < |s| :: s[p] <= s[q]; print s; } /////////////////////////////////////////////////////////////// // Hér lýkur óbreytanlega hluta skrárinnar. // Hér fyrir aftan er sá hluti sem þið eigið að breyta til að // útfæra afbrigði af selection sort. /////////////////////////////////////////////////////////////// // Selection sort sem raðar poka í runu. // Klárið að forrita þetta fall. method Sort( m: multiset<int> ) returns ( s: seq<int> ) // Setjið viðeigandi ensures klausur hér ensures multiset(s) == m; ensures forall p,q | 0 <= p < q < |s| :: s[p] <= s[q]; { // Setjið viðeigandi frumstillingar á m' og s hér. // m' er ný staðvær breyta en s er skilabreyta. s := []; var m' := m; while m' != multiset{} // Ekki breyta fastayrðingu lykkju decreases m'; invariant m == m'+multiset(s); invariant forall p,q | 0 <= p < q < |s| :: s[p] <= s[q]; invariant forall z | z in m' :: forall r | 0 <= r < |s| :: z >= s[r]; { // Setjið viðeigandi stofn í lykkjuna hér var x := MinOfMultiset(m'); m' := m' - multiset{x}; s := s + [x]; } return s; }
// Höfundur spurningar: Snorri Agnarsson, snorri@hi.is // Permalink spurningar: https://rise4fun.com/Dafny/dtcnY // Höfundur lausnar: Alexander Guðmundsson // Permalink lausnar: https://rise4fun.com/Dafny/ybUCz /////////////////////////////////////////////////////////////// // Hér byrjar óbreytanlegi hluti skrárinnar. // Fyrir aftan þann hluta er sá hluti sem þið eigið að breyta. /////////////////////////////////////////////////////////////// // Hjálparfall sem finnur minnsta gildi í poka method MinOfMultiset( m: multiset<int> ) returns( min: int ) requires m != multiset{}; ensures min in m; ensures forall z | z in m :: min <= z; { min :| min in m; var done := multiset{min}; var m' := m-done; while m' != multiset{} { var z :| z in m'; done := done+multiset{z}; m' := m'-multiset{z}; if z < min { min := z; } } } // Ekki má breyta þessu falli. method Test( m: multiset<int> ) { var s := Sort(m); } method Main() { var m := multiset{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9}; var s := Sort(m); print s; } /////////////////////////////////////////////////////////////// // Hér lýkur óbreytanlega hluta skrárinnar. // Hér fyrir aftan er sá hluti sem þið eigið að breyta til að // útfæra afbrigði af selection sort. /////////////////////////////////////////////////////////////// // Selection sort sem raðar poka í runu. // Klárið að forrita þetta fall. method Sort( m: multiset<int> ) returns ( s: seq<int> ) // Setjið viðeigandi ensures klausur hér ensures multiset(s) == m; ensures forall p,q | 0 <= p < q < |s| :: s[p] <= s[q]; { // Setjið viðeigandi frumstillingar á m' og s hér. // m' er ný staðvær breyta en s er skilabreyta. s := []; var m' := m; while m' != multiset{} // Ekki breyta fastayrðingu lykkju { // Setjið viðeigandi stofn í lykkjuna hér var x := MinOfMultiset(m'); m' := m' - multiset{x}; s := s + [x]; } return s; }
191
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 8_H8.dfy
// Höfundur spurningar: Snorri Agnarsson, snorri@hi.is // Permalink spurningar: https://rise4fun.com/Dafny/GW7a // Höfundur lausnar: Alexander Guðmundsson // Permalink lausnar: https://www.rise4fun.com/Dafny/JPGct // Klárið að forrita föllin tvö. method Partition( m: multiset<int> ) returns( pre: multiset<int>, p: int, post: multiset<int> ) requires |m| > 0; ensures p in m; ensures m == pre+multiset{p}+post; ensures forall z | z in pre :: z <= p; ensures forall z | z in post :: z >= p; { p :| p in m; var m' := m; m' := m' - multiset{p}; pre := multiset{}; post := multiset{}; while m' != multiset{} decreases m'; invariant m == m' + pre + multiset{p} + post; invariant forall k | k in pre :: k <= p; invariant forall k | k in post :: k >= p; { var temp :| temp in m'; m' := m' - multiset{temp}; if temp <= p { pre := pre + multiset{temp}; } else { post := post + multiset{temp}; } } return pre,p,post; } method QuickSelect( m: multiset<int>, k: int ) returns( pre: multiset<int>, kth: int, post: multiset<int> ) decreases m; requires 0 <= k < |m|; ensures kth in m; ensures m == pre+multiset{kth}+post; ensures |pre| == k; ensures forall z | z in pre :: z <= kth; ensures forall z | z in post :: z >= kth; { pre,kth,post := Partition(m); assert m == pre + multiset{kth} + post; if |pre| != k { if k > |pre| { var pre',p,post' := QuickSelect(post,k-|pre| - 1); assert pre' + multiset{p} + post' == post; pre := pre + multiset{kth} + pre'; post := post - pre' - multiset{p}; kth := p; } else if k < |pre| { var pre',p,post' := QuickSelect(pre,k); pre := pre - multiset{p} - post'; post := post + multiset{kth} + post'; kth := p; } } else{ return pre,kth,post; } }
// Höfundur spurningar: Snorri Agnarsson, snorri@hi.is // Permalink spurningar: https://rise4fun.com/Dafny/GW7a // Höfundur lausnar: Alexander Guðmundsson // Permalink lausnar: https://www.rise4fun.com/Dafny/JPGct // Klárið að forrita föllin tvö. method Partition( m: multiset<int> ) returns( pre: multiset<int>, p: int, post: multiset<int> ) requires |m| > 0; ensures p in m; ensures m == pre+multiset{p}+post; ensures forall z | z in pre :: z <= p; ensures forall z | z in post :: z >= p; { p :| p in m; var m' := m; m' := m' - multiset{p}; pre := multiset{}; post := multiset{}; while m' != multiset{} { var temp :| temp in m'; m' := m' - multiset{temp}; if temp <= p { pre := pre + multiset{temp}; } else { post := post + multiset{temp}; } } return pre,p,post; } method QuickSelect( m: multiset<int>, k: int ) returns( pre: multiset<int>, kth: int, post: multiset<int> ) requires 0 <= k < |m|; ensures kth in m; ensures m == pre+multiset{kth}+post; ensures |pre| == k; ensures forall z | z in pre :: z <= kth; ensures forall z | z in post :: z >= kth; { pre,kth,post := Partition(m); if |pre| != k { if k > |pre| { var pre',p,post' := QuickSelect(post,k-|pre| - 1); pre := pre + multiset{kth} + pre'; post := post - pre' - multiset{p}; kth := p; } else if k < |pre| { var pre',p,post' := QuickSelect(pre,k); pre := pre - multiset{p} - post'; post := post + multiset{kth} + post'; kth := p; } } else{ return pre,kth,post; } }
192
Dafny_tmp_tmp0wu8wmfr_tests_F1a.dfy
method F() returns ( r: int) ensures r <= 0 { r := 0; } method Main() { var x := F(); assert x <= 0; x := x-1; assert x <= -1; print x; } method Mid( p: int, q: int) returns ( m: int ) // | ... | ??? | ... | // p m q requires p <= q; ensures p<= m <= q; ensures m-p <= q-m; ensures 0 <= (q-m)-(m-p) <= 1; { m := (p+q)/2; assert m == p+(q-p)/2; }
method F() returns ( r: int) ensures r <= 0 { r := 0; } method Main() { var x := F(); x := x-1; print x; } method Mid( p: int, q: int) returns ( m: int ) // | ... | ??? | ... | // p m q requires p <= q; ensures p<= m <= q; ensures m-p <= q-m; ensures 0 <= (q-m)-(m-p) <= 1; { m := (p+q)/2; }
193
Dafny_tmp_tmp0wu8wmfr_tests_InsertionSortSeq.dfy
// Insertion sort. // // Author: Snorri Agnarsson, snorri@hi.is predicate IsSorted( s: seq<int> ) { forall p,q | 0<=p<q<|s| :: s[p]<=s[q] } method InsertionSort( s: seq<int> ) returns ( r: seq<int> ) ensures multiset(r) == multiset(s); ensures IsSorted(r); { r := []; var rest := s; while rest != [] decreases rest; invariant multiset(s) == multiset(r)+multiset(rest); invariant IsSorted(r); { var x := rest[0]; assert rest == rest[0..1]+rest[1..]; rest := rest[1..]; var k := |r|; while k>0 && r[k-1]>x invariant 0 <= k <= |r|; invariant forall p | k<=p<|r| :: r[p]>x; { k := k-1; } assert r == r[..k]+r[k..]; r := r[..k]+[x]+r[k..]; } }
// Insertion sort. // // Author: Snorri Agnarsson, snorri@hi.is predicate IsSorted( s: seq<int> ) { forall p,q | 0<=p<q<|s| :: s[p]<=s[q] } method InsertionSort( s: seq<int> ) returns ( r: seq<int> ) ensures multiset(r) == multiset(s); ensures IsSorted(r); { r := []; var rest := s; while rest != [] { var x := rest[0]; rest := rest[1..]; var k := |r|; while k>0 && r[k-1]>x { k := k-1; } r := r[..k]+[x]+r[k..]; } }
194
Dafny_tmp_tmp0wu8wmfr_tests_Search1000.dfy
// Author: Snorri Agnarsson, snorri@hi.is // Search1000 is a Dafny version of a function shown // by Jon Bentley in his old Programming Pearls // column in CACM. Surprisingly Dafny needs no help // to verify the function. method Search1000( a: array<int>, x: int ) returns ( k: int ) requires a.Length >= 1000; requires forall p,q | 0 <= p < q < 1000 :: a[p] <= a[q]; ensures 0 <= k <= 1000; ensures forall r | 0 <= r < k :: a[r] < x; ensures forall r | k <= r < 1000 :: a[r] >= x; { k := 0; if a[500] < x { k := 489; } // a: | <x | ??? | >= x| // ^ ^ ^ ^ // 0 k k+511 1000 if a[k+255] < x { k := k+256; } // a: | <x | ??? | >= x| // ^ ^ ^ ^ // 0 k k+255 1000 if a[k+127] < x { k := k+128; } if a[k+63] < x { k := k+64; } if a[k+31] < x { k := k+32; } if a[k+15] < x { k := k+16; } if a[k+7] < x { k := k+8; } if a[k+3] < x { k := k+4; } if a[k+1] < x { k := k+2; } // a: | <x | ??? | >= x| // ^ ^ ^ ^ // 0 k k+1 1000 if a[k] < x { k := k+1; } // a: | <x | >= x| // ^ ^ ^ // 0 k 1000 } // Is2Pow(n) is true iff n==2^k for some k>=0. predicate Is2Pow( n: int ) decreases n; { if n < 1 then false else if n == 1 then true else n%2 == 0 && Is2Pow(n/2) } // This method is a binary search that only works for array // segments of size n == 2^k-1 for some k>=0. method Search2PowLoop( a: array<int>, i: int, n: int, x: int ) returns ( k: int ) requires 0 <= i <= i+n <= a.Length; requires forall p,q | i <= p < q < i+n :: a[p] <= a[q]; requires Is2Pow(n+1); ensures i <= k <= i+n; ensures forall r | i <= r < k :: a[r] < x; ensures forall r | k <= r < i+n :: a[r] >= x; { k := i; var c := n; while c != 0 decreases c; invariant Is2Pow(c+1); invariant i <= k <= k+c <= i+n; invariant forall r | i <= r < k :: a[r] < x; invariant forall r | k+c <= r < i+n :: a[r] >= x; { c := c/2; if a[k+c] < x { k := k+c+1; } } } // This method is a binary search that only works for array // segments of size n == 2^k-1 for some k>=0. method Search2PowRecursive( a: array<int>, i: int, n: int, x: int ) returns ( k: int ) decreases n; requires 0 <= i <= i+n <= a.Length; requires forall p,q | i <= p < q < i+n :: a[p] <= a[q]; requires Is2Pow(n+1); ensures i <= k <= i+n; ensures forall r | i <= r < k :: a[r] < x; ensures forall r | k <= r < i+n :: a[r] >= x; { if n==0 { return i; } if a[i+n/2] < x { k := Search2PowRecursive(a,i+n/2+1,n/2,x); } else { k := Search2PowRecursive(a,i,n/2,x); } }
// Author: Snorri Agnarsson, snorri@hi.is // Search1000 is a Dafny version of a function shown // by Jon Bentley in his old Programming Pearls // column in CACM. Surprisingly Dafny needs no help // to verify the function. method Search1000( a: array<int>, x: int ) returns ( k: int ) requires a.Length >= 1000; requires forall p,q | 0 <= p < q < 1000 :: a[p] <= a[q]; ensures 0 <= k <= 1000; ensures forall r | 0 <= r < k :: a[r] < x; ensures forall r | k <= r < 1000 :: a[r] >= x; { k := 0; if a[500] < x { k := 489; } // a: | <x | ??? | >= x| // ^ ^ ^ ^ // 0 k k+511 1000 if a[k+255] < x { k := k+256; } // a: | <x | ??? | >= x| // ^ ^ ^ ^ // 0 k k+255 1000 if a[k+127] < x { k := k+128; } if a[k+63] < x { k := k+64; } if a[k+31] < x { k := k+32; } if a[k+15] < x { k := k+16; } if a[k+7] < x { k := k+8; } if a[k+3] < x { k := k+4; } if a[k+1] < x { k := k+2; } // a: | <x | ??? | >= x| // ^ ^ ^ ^ // 0 k k+1 1000 if a[k] < x { k := k+1; } // a: | <x | >= x| // ^ ^ ^ // 0 k 1000 } // Is2Pow(n) is true iff n==2^k for some k>=0. predicate Is2Pow( n: int ) { if n < 1 then false else if n == 1 then true else n%2 == 0 && Is2Pow(n/2) } // This method is a binary search that only works for array // segments of size n == 2^k-1 for some k>=0. method Search2PowLoop( a: array<int>, i: int, n: int, x: int ) returns ( k: int ) requires 0 <= i <= i+n <= a.Length; requires forall p,q | i <= p < q < i+n :: a[p] <= a[q]; requires Is2Pow(n+1); ensures i <= k <= i+n; ensures forall r | i <= r < k :: a[r] < x; ensures forall r | k <= r < i+n :: a[r] >= x; { k := i; var c := n; while c != 0 { c := c/2; if a[k+c] < x { k := k+c+1; } } } // This method is a binary search that only works for array // segments of size n == 2^k-1 for some k>=0. method Search2PowRecursive( a: array<int>, i: int, n: int, x: int ) returns ( k: int ) requires 0 <= i <= i+n <= a.Length; requires forall p,q | i <= p < q < i+n :: a[p] <= a[q]; requires Is2Pow(n+1); ensures i <= k <= i+n; ensures forall r | i <= r < k :: a[r] < x; ensures forall r | k <= r < i+n :: a[r] >= x; { if n==0 { return i; } if a[i+n/2] < x { k := Search2PowRecursive(a,i+n/2+1,n/2,x); } else { k := Search2PowRecursive(a,i,n/2,x); } }
195
Dafny_tmp_tmp0wu8wmfr_tests_SumIntsLoop.dfy
function sumInts( n: int ): int requires n >= 0; { if n == 0 then 0 else sumInts(n-1)+n } method SumIntsLoop( n: int ) returns ( s: int ) requires n >= 0; ensures s == sumInts(n) ensures s == n*(n+1)/2; { s := 0; var k := 0; while k != n decreases n-k; invariant 0 <= k <= n; invariant s == sumInts(k) invariant s == k*(k+1)/2; { k := k+1; s := s+k; } } method Main() { var x := SumIntsLoop(100); print x; }
function sumInts( n: int ): int requires n >= 0; { if n == 0 then 0 else sumInts(n-1)+n } method SumIntsLoop( n: int ) returns ( s: int ) requires n >= 0; ensures s == sumInts(n) ensures s == n*(n+1)/2; { s := 0; var k := 0; while k != n { k := k+1; s := s+k; } } method Main() { var x := SumIntsLoop(100); print x; }
196
Dafny_tmp_tmpj88zq5zt_2-Kontrakte_max.dfy
method max(a: array<int>, b: array<int>, i: int, j: int) returns (m: int) requires 0 <= i < a.Length requires 0 <= j < b.Length ensures a[i] > b[j] ==> m == a[i] ensures a[i] <= b[j] ==> m == b[j] { if a[i] > b[j] { m := a[i]; } else { m := b[j]; } } method testMax(a:array<int>, b:array<int>, i: int, j: int) requires 0 <= i < a.Length requires 0 <= j < b.Length { var max := max(a,b,i,j); assert a[i] > b[j] ==> max == a[i]; assert a[i] <= b[j] ==> max == b[j]; }
method max(a: array<int>, b: array<int>, i: int, j: int) returns (m: int) requires 0 <= i < a.Length requires 0 <= j < b.Length ensures a[i] > b[j] ==> m == a[i] ensures a[i] <= b[j] ==> m == b[j] { if a[i] > b[j] { m := a[i]; } else { m := b[j]; } } method testMax(a:array<int>, b:array<int>, i: int, j: int) requires 0 <= i < a.Length requires 0 <= j < b.Length { var max := max(a,b,i,j); }
197
Dafny_tmp_tmpj88zq5zt_2-Kontrakte_reverse3.dfy
method swap3(a: array<int>, h: int, i: int, j: int) modifies a requires 0 <= h < a.Length requires 0 <= i < a.Length requires 0 <= j < a.Length requires i != j && j != h && h != i; ensures a[h] == old(a[i]); ensures a[j] == old(a[h]); ensures a[i] == old(a[j]); ensures forall k: int :: 0 <= k < a.Length && k != h && k != i && k != j ==> a[k] == old(a[k]); { var tmp := a[h]; a[h] := a[i]; a[i] := a[j]; a[j] := tmp; } method testSwap3(a: array<int>, h: int, i: int, j:int ) modifies a requires 0 <= h < a.Length requires 0 <= i < a.Length requires 0 <= j < a.Length requires i != j && j != h && h != i; { swap3(a, h, i, j); assert a[h] == old(a[i]); assert a[j] == old(a[h]); assert a[i] == old(a[j]); assert forall k: int :: 0 <= k < a.Length && k != h && k != i && k != j ==> a[k] == old(a[k]); }
method swap3(a: array<int>, h: int, i: int, j: int) modifies a requires 0 <= h < a.Length requires 0 <= i < a.Length requires 0 <= j < a.Length requires i != j && j != h && h != i; ensures a[h] == old(a[i]); ensures a[j] == old(a[h]); ensures a[i] == old(a[j]); ensures forall k: int :: 0 <= k < a.Length && k != h && k != i && k != j ==> a[k] == old(a[k]); { var tmp := a[h]; a[h] := a[i]; a[i] := a[j]; a[j] := tmp; } method testSwap3(a: array<int>, h: int, i: int, j:int ) modifies a requires 0 <= h < a.Length requires 0 <= i < a.Length requires 0 <= j < a.Length requires i != j && j != h && h != i; { swap3(a, h, i, j); }
198
Dafny_tmp_tmpmvs2dmry_SlowMax.dfy
function max(x:nat, y:nat) : nat { if (x < y) then y else x } method slow_max(a: nat, b: nat) returns (z: nat) ensures z == max(a, b) { z := 0; var x := a; var y := b; while (z < x && z < y) invariant x >=0; invariant y >=0; invariant z == a - x && z == b - y; invariant a-x == b-y decreases x,y; { z := z + 1; x := x - 1; y := y - 1; } if (x <= y) { return b; } else { return a;} }
function max(x:nat, y:nat) : nat { if (x < y) then y else x } method slow_max(a: nat, b: nat) returns (z: nat) ensures z == max(a, b) { z := 0; var x := a; var y := b; while (z < x && z < y) { z := z + 1; x := x - 1; y := y - 1; } if (x <= y) { return b; } else { return a;} }
199
Dafny_tmp_tmpmvs2dmry_examples1.dfy
method Abs(x:int) returns (y:int) ensures y>=0; ensures x>=0 ==> x == y; ensures x<0 ==> -x == y; ensures y == abs(x); // use this instead of line 3,4 { if(x<0) { return -x; } else{ return x; } } function abs(x: int): int{ if x>0 then x else -x } method Testing(){ var v:= Abs(-3); assert v >= 0; assert v == 3; } method MultiReturn(x:int, y:int) returns (more:int, less:int) requires y>=0; ensures less <= x <= more; { more := x + y; less := x - y; } method Max(x:int, y:int) returns (a:int) ensures a == x || a == y; ensures x > y ==> a == x; ensures x <= y ==> a == y; { if ( x > y ) { a := x; } else { a := y; } }
method Abs(x:int) returns (y:int) ensures y>=0; ensures x>=0 ==> x == y; ensures x<0 ==> -x == y; ensures y == abs(x); // use this instead of line 3,4 { if(x<0) { return -x; } else{ return x; } } function abs(x: int): int{ if x>0 then x else -x } method Testing(){ var v:= Abs(-3); } method MultiReturn(x:int, y:int) returns (more:int, less:int) requires y>=0; ensures less <= x <= more; { more := x + y; less := x - y; } method Max(x:int, y:int) returns (a:int) ensures a == x || a == y; ensures x > y ==> a == x; ensures x <= y ==> a == y; { if ( x > y ) { a := x; } else { a := y; } }