id
stringlengths
3
3
name
stringlengths
3
3
docstring
stringlengths
18
18
code
stringlengths
129
20.6k
ground_truth
stringlengths
148
21.8k
test_file
stringlengths
15
119
135
135
Dafny program: 135
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; }
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; }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_a3_search_findPositionOfIndex.dfy
136
136
Dafny program: 136
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; } } }
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; } } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week10_BoundedQueue_01.dfy
137
137
Dafny program: 137
class ExtensibleArray<T(0)> { // abstract state ghost var Elements: seq<T> ghost var Repr: set<object> //concrete state var front: array?<T> var depot: ExtensibleArray?<array<T>> var length: int // number of elements var M: int // number of elements in depot ghost predicate Valid() reads this, Repr ensures Valid() ==> this in Repr { // Abstraction relation: Repr this in Repr && (front != null ==> front in Repr) && (depot != null ==> depot in Repr && depot.Repr <= Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] in Repr) && // Standard concrete invariants: Aliasing (depot != null ==> this !in depot.Repr && front !in depot.Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] !in depot.Repr && depot.Elements[j] != front && forall k :: 0 <= k < |depot.Elements| && k != j ==> depot.Elements[j] != depot.Elements[k]) && // Concrete state invariants (front != null ==> front.Length == 256) && (depot != null ==> depot.Valid() && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j].Length == 256) && (length == M <==> front == null) && M == (if depot == null then 0 else 256 * |depot.Elements|) && // Abstraction relation: Elements length == |Elements| && M <= |Elements| < M + 256 && (forall i :: 0 <= i < M ==> Elements[i] == depot.Elements[i / 256][i % 256]) && (forall i :: M <= i < length ==> Elements[i] == front[i - M]) } constructor () ensures Valid() && fresh(Repr) && Elements == [] { front, depot := null, null; length, M := 0, 0; Elements, Repr := [], {this}; } function Get(i: int): T requires Valid() && 0 <= i < |Elements| ensures Get(i) == Elements[i] reads Repr { if M <= i then front[i - M] else depot.Get(i/256)[i%256] } method Set(i: int, t: T) requires Valid() && 0 <= i < |Elements| modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements)[i := t] { if M <= i { front[i - M] := t; } else { depot.Get(i/256)[i%256] := t; } Elements := Elements[i := t]; } method Add(t: T) requires Valid() modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements) + [t] { if front == null { front := new T[256]; Repr := Repr + {front}; } front[length-M] := t; length := length + 1; Elements := Elements + [t]; if length == M + 256 { if depot == null { depot := new ExtensibleArray(); } depot.Add(front); Repr := Repr + depot.Repr; M := M + 256; front := null; } } }
class ExtensibleArray<T(0)> { // abstract state ghost var Elements: seq<T> ghost var Repr: set<object> //concrete state var front: array?<T> var depot: ExtensibleArray?<array<T>> var length: int // number of elements var M: int // number of elements in depot ghost predicate Valid() decreases Repr +{this} reads this, Repr ensures Valid() ==> this in Repr { // Abstraction relation: Repr this in Repr && (front != null ==> front in Repr) && (depot != null ==> depot in Repr && depot.Repr <= Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] in Repr) && // Standard concrete invariants: Aliasing (depot != null ==> this !in depot.Repr && front !in depot.Repr && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j] !in depot.Repr && depot.Elements[j] != front && forall k :: 0 <= k < |depot.Elements| && k != j ==> depot.Elements[j] != depot.Elements[k]) && // Concrete state invariants (front != null ==> front.Length == 256) && (depot != null ==> depot.Valid() && forall j :: 0 <= j < |depot.Elements| ==> depot.Elements[j].Length == 256) && (length == M <==> front == null) && M == (if depot == null then 0 else 256 * |depot.Elements|) && // Abstraction relation: Elements length == |Elements| && M <= |Elements| < M + 256 && (forall i :: 0 <= i < M ==> Elements[i] == depot.Elements[i / 256][i % 256]) && (forall i :: M <= i < length ==> Elements[i] == front[i - M]) } constructor () ensures Valid() && fresh(Repr) && Elements == [] { front, depot := null, null; length, M := 0, 0; Elements, Repr := [], {this}; } function Get(i: int): T requires Valid() && 0 <= i < |Elements| ensures Get(i) == Elements[i] reads Repr { if M <= i then front[i - M] else depot.Get(i/256)[i%256] } method Set(i: int, t: T) requires Valid() && 0 <= i < |Elements| modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements)[i := t] { if M <= i { front[i - M] := t; } else { depot.Get(i/256)[i%256] := t; } Elements := Elements[i := t]; } method Add(t: T) requires Valid() modifies Repr ensures Valid() && fresh(Repr - old(Repr)) ensures Elements == old(Elements) + [t] decreases |Elements| { if front == null { front := new T[256]; Repr := Repr + {front}; } front[length-M] := t; length := length + 1; Elements := Elements + [t]; if length == M + 256 { if depot == null { depot := new ExtensibleArray(); } depot.Add(front); Repr := Repr + depot.Repr; M := M + 256; front := null; } } }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week10_ExtensibleArray.dfy
138
138
Dafny program: 138
ghost function Hash(s:string):int { SumChars(s) % 137 } ghost function SumChars(s: string):int { if |s| == 0 then 0 else s[|s| - 1] as int + SumChars(s[..|s| -1]) } class CheckSumCalculator{ var data: string var cs:int ghost predicate Valid() reads this { cs == Hash(data) } constructor () ensures Valid() && data == "" { data, cs := "", 0; } method Append(d:string) requires Valid() modifies this ensures Valid() && data == old(data) + d { var i := 0; while i != |d| { cs := (cs + d[i] as int) % 137; data := data + [d[i]]; i := i +1; } } function GetData(): string requires Valid() reads this ensures Hash(GetData()) == Checksum() { data } function Checksum(): int requires Valid() reads this ensures Checksum() == Hash(data) { cs } } method Main() { /* var m:= new CheckSumCalculator(); m.Append("g"); m.Append("Grass"); var c:= m.Checksum(); var g:= m.GetData(); print "(m.cs)Checksum is " ,m.cs,"\n"; print "(c)Checksum is " ,c,"\n"; print "(m.data)Checksum is " ,m.data,"\n"; print "(g)Checksum is " ,g,"\n"; var tmpStr := "abcde"; var tmpStrOne := "LLLq"; var tmpSet := {'a','c'}; var tmpFresh := {'a','b'}; var tmpnum := 1; print "tmp is ", tmpSet - tmpFresh; var newArray := new int[10]; newArray[0]:= 0; */ var newSeq := ['a','b','c','d','e','f','g','h']; var newSeqTwo := ['h','g','f','e','d','c','b','a']; var newSet : set<int>; newSet := {1,2,3,4,5}; var newSetTwo := {6,7,8,9,10}; print "element is newset ", newSet,"\n"; var newArray := new int [99]; newArray[0] := 99; newArray[1] := 2; print "element is ? ", |[newArray]|,"\n"; var tmpSet := {'a','c'}; var tmpFresh := {'c'}; print "tmp is ", tmpSet - tmpFresh; var newMap := map[]; newMap := newMap[1:=2]; var nnewMap := map[3:=444]; print "keys is ",newMap.Keys,newMap.Values; print "value is", nnewMap.Keys,nnewMap.Values; }
ghost function Hash(s:string):int { SumChars(s) % 137 } ghost function SumChars(s: string):int { if |s| == 0 then 0 else s[|s| - 1] as int + SumChars(s[..|s| -1]) } class CheckSumCalculator{ var data: string var cs:int ghost predicate Valid() reads this { cs == Hash(data) } constructor () ensures Valid() && data == "" { data, cs := "", 0; } method Append(d:string) requires Valid() modifies this ensures Valid() && data == old(data) + d { var i := 0; while i != |d| invariant 0<= i <= |d| invariant Valid() invariant data == old(data) + d[..i] { cs := (cs + d[i] as int) % 137; data := data + [d[i]]; i := i +1; } } function GetData(): string requires Valid() reads this ensures Hash(GetData()) == Checksum() { data } function Checksum(): int requires Valid() reads this ensures Checksum() == Hash(data) { cs } } method Main() { /* var m:= new CheckSumCalculator(); m.Append("g"); m.Append("Grass"); var c:= m.Checksum(); var g:= m.GetData(); print "(m.cs)Checksum is " ,m.cs,"\n"; print "(c)Checksum is " ,c,"\n"; print "(m.data)Checksum is " ,m.data,"\n"; print "(g)Checksum is " ,g,"\n"; var tmpStr := "abcde"; var tmpStrOne := "LLLq"; var tmpSet := {'a','c'}; var tmpFresh := {'a','b'}; var tmpnum := 1; print "tmp is ", tmpSet - tmpFresh; var newArray := new int[10]; newArray[0]:= 0; */ var newSeq := ['a','b','c','d','e','f','g','h']; var newSeqTwo := ['h','g','f','e','d','c','b','a']; var newSet : set<int>; newSet := {1,2,3,4,5}; var newSetTwo := {6,7,8,9,10}; print "element is newset ", newSet,"\n"; var newArray := new int [99]; newArray[0] := 99; newArray[1] := 2; print "element is ? ", |[newArray]|,"\n"; var tmpSet := {'a','c'}; var tmpFresh := {'c'}; print "tmp is ", tmpSet - tmpFresh; var newMap := map[]; newMap := newMap[1:=2]; var nnewMap := map[3:=444]; print "keys is ",newMap.Keys,newMap.Values; print "value is", nnewMap.Keys,nnewMap.Values; }
Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week8_CheckSumCalculator.dfy
142
142
Dafny program: 142
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; }
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; }
Dafny_Programs_tmp_tmp99966ew4_binary_search.dfy
143
143
Dafny program: 143
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; }
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; }
Dafny_Programs_tmp_tmp99966ew4_lemma.dfy
145
145
Dafny program: 145
predicate P(x: int) predicate Q(x: int) method test() requires forall x {:trigger P(x)} :: P(x) && Q(x) ensures Q(0) { }
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); }
Dafny_Programs_tmp_tmp99966ew4_trig.dfy
146
146
Dafny program: 146
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; // } // }
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; // } // }
Dafny_Verify_tmp_tmphq7j0row_AI_agent_validation_examples.dfy
147
147
Dafny program: 147
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_ComputePower.dfy
148
148
Dafny program: 148
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_CopyMatrix.dfy
149
149
Dafny program: 149
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_Cube.dfy
150
150
Dafny program: 150
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_DoubleArray.dfy
151
151
Dafny program: 151
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_IncrementMatrix.dfy
152
152
Dafny program: 152
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_RotateRight.dfy
153
153
Dafny program: 153
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_28.dfy
154
154
Dafny program: 154
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_37.dfy
155
155
Dafny program: 155
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 {} } }
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 {} } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_38.dfy
156
156
Dafny program: 156
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_41.dfy
157
157
Dafny program: 157
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; }
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; }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_BinarySearch.dfy
158
158
Dafny program: 158
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_SumArray.dfy
160
160
Dafny program: 160
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_07.dfy
161
161
Dafny program: 161
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_11.dfy
162
162
Dafny program: 162
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_normal_data_completion_MaxPerdV2.dfy
163
163
Dafny program: 163
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_15.dfy
164
164
Dafny program: 164
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_ComputePower.dfy
165
165
Dafny program: 165
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; }
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; }
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Count.dfy
166
166
Dafny program: 166
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_LinearSearch.dfy
167
167
Dafny program: 167
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Minimum.dfy
168
168
Dafny program: 168
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Mult.dfy
169
169
Dafny program: 169
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Generated_Code_rand.dfy
173
173
Dafny program: 173
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; } }
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; }
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_LoopInvariant.dfy
175
175
Dafny program: 175
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_Test_Cases_solved_1_select.dfy
178
178
Dafny program: 178
// 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; } }
// 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; } }
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_07.dfy
179
179
Dafny program: 179
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))))))
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))))))
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_11.dfy
180
180
Dafny program: 180
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)))))
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)))))
Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_15.dfy
182
182
Dafny program: 182
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_Min.dfy
183
183
Dafny program: 183
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_SmallNum.dfy
184
184
Dafny program: 184
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_Square.dfy
185
185
Dafny program: 185
// 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; } }
// 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; } }
Dafny_Verify_tmp_tmphq7j0row_dataset_detailed_examples_SelectionSort.dfy
186
186
Dafny program: 186
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; } }
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; } }
Dafny_Verify_tmp_tmphq7j0row_dataset_error_data_real_error_IsEven_success_1.dfy
187
187
Dafny program: 187
// 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; }
// 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; }
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 1_LinearSearch.dfy
188
188
Dafny program: 188
// 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); }
// 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; }
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 2_BinarySearchDec.dfy
189
189
Dafny program: 189
// 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; }
// 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; }
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 3_InsertionSortMultiset.dfy
190
190
Dafny program: 190
// 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; }
// 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; }
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 3_SelectionSortMultiset.dfy
191
191
Dafny program: 191
// 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; } }
// 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; } }
Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 8_H8.dfy
193
193
Dafny program: 193
// 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..]; } }
// 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..]; } }
Dafny_tmp_tmp0wu8wmfr_tests_InsertionSortSeq.dfy
194
194
Dafny program: 194
// 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); } }
// 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); } }
Dafny_tmp_tmp0wu8wmfr_tests_Search1000.dfy
195
195
Dafny program: 195
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; }
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; }
Dafny_tmp_tmp0wu8wmfr_tests_SumIntsLoop.dfy
198
198
Dafny program: 198
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;} }
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;} }
Dafny_tmp_tmpmvs2dmry_SlowMax.dfy
200
200
Dafny program: 200
method add_by_inc(x: nat, y:nat) returns (z:nat) ensures z == x+y; { z := x; var i := 0; while (i < y) { z := z+1; i := i+1; } } method Product(m: nat, n:nat) returns (res:nat) ensures res == m*n; { var m1: nat := m; res:=0; while (m1 != 0) { var n1: nat := n; while (n1 != 0) { res := res+1; n1 := n1-1; } m1 := m1-1; } } method gcdCalc(m: nat, n: nat) returns (res: nat) requires m>0 && n>0; ensures res == gcd(m,n); { var m1 : nat := m; var n1 : nat := n; while (m1 != n1) { if( m1>n1) { m1 := m1- n1; } else { n1:= n1-m1; } } return n1; } function gcd(m: nat, n: nat) : nat requires m>0 && n>0; { if(m==n) then n else if( m > n) then gcd(m-n,n) else gcd(m, n-m) } method exp_by_sqr(x0: real, n0: nat) returns (r:real) requires x0 >= 0.0; ensures r == exp(x0, n0); { if(n0 == 0) {return 1.0;} if(x0 == 0.0) {return 0.0;} var x,n,y := x0, n0, 1.0; while(n>1) { if( n % 2 == 0) { assume (exp(x,n) == exp(x*x,n/2)); x := x*x; n:= n/2; } else { assume (exp(x,n) == exp(x*x,(n-1)/2) * x); y:=x*y; x:=x*x; n:=(n-1)/2; } } // assert (exp(x0,n0) == exp(x,n) * y); // assert (x*y == exp(x0,n0)); return x*y; } function exp(x: real, n: nat) :real { if(n == 0) then 1.0 else if (x==0.0) then 0.0 else if (n ==0 && x == 0.0) then 1.0 else x*exp(x, n-1) } // method add_by_inc_vc(x: int, y:int) returns (z:int) // { // assume x>=0 && y>=0; // z := x; // var i := 0; // assert 0 <= i <= y && z == x + i; // z,i = *,*; // assume 0 <= i <= y && z == x + i; // if (i < y) // { // ghost var rank0 := y-i // z := z+1; // i := i+1; // assert(y-i < rank0) // ghost var rank1 := y-i // assert(rank1 < rank0) // assert(rank1 >=0) // assert 0 <= i <= y && z == x + i; // assume(false); // } // assert (z == x+y); // assert (i == y); // return z; // }
method add_by_inc(x: nat, y:nat) returns (z:nat) ensures z == x+y; { z := x; var i := 0; while (i < y) decreases y-i; invariant 0 <= i <= y; invariant z == x + i; { z := z+1; i := i+1; } assert (z == x+y); assert (i == y); } method Product(m: nat, n:nat) returns (res:nat) ensures res == m*n; { var m1: nat := m; res:=0; while (m1 != 0) invariant 0 <= m1 <= m; decreases m1; invariant res == (m-m1)*n; { var n1: nat := n; while (n1 != 0) invariant 0 <= n1 <= n; decreases n1; invariant res == (m-m1)*n + (n-n1); { res := res+1; n1 := n1-1; } m1 := m1-1; } } method gcdCalc(m: nat, n: nat) returns (res: nat) requires m>0 && n>0; ensures res == gcd(m,n); { var m1 : nat := m; var n1 : nat := n; while (m1 != n1) invariant 0< m1 <=m; invariant 0 < n1 <=n; invariant gcd(m,n) == gcd (m1,n1) decreases m1+n1; { if( m1>n1) { m1 := m1- n1; } else { n1:= n1-m1; } } return n1; } function gcd(m: nat, n: nat) : nat requires m>0 && n>0; decreases m+n { if(m==n) then n else if( m > n) then gcd(m-n,n) else gcd(m, n-m) } method exp_by_sqr(x0: real, n0: nat) returns (r:real) requires x0 >= 0.0; ensures r == exp(x0, n0); { if(n0 == 0) {return 1.0;} if(x0 == 0.0) {return 0.0;} var x,n,y := x0, n0, 1.0; while(n>1) invariant 1<=n<=n0; invariant exp(x0,n0) == exp(x,n) * y; decreases n; { if( n % 2 == 0) { assume (exp(x,n) == exp(x*x,n/2)); x := x*x; n:= n/2; } else { assume (exp(x,n) == exp(x*x,(n-1)/2) * x); y:=x*y; x:=x*x; n:=(n-1)/2; } } // assert (exp(x0,n0) == exp(x,n) * y); // assert (x*y == exp(x0,n0)); return x*y; } function exp(x: real, n: nat) :real decreases n; { if(n == 0) then 1.0 else if (x==0.0) then 0.0 else if (n ==0 && x == 0.0) then 1.0 else x*exp(x, n-1) } // method add_by_inc_vc(x: int, y:int) returns (z:int) // { // assume x>=0 && y>=0; // z := x; // var i := 0; // assert 0 <= i <= y && z == x + i; // z,i = *,*; // assume 0 <= i <= y && z == x + i; // if (i < y) // { // ghost var rank0 := y-i // z := z+1; // i := i+1; // assert(y-i < rank0) // ghost var rank1 := y-i // assert(rank1 < rank0) // assert(rank1 >=0) // assert 0 <= i <= y && z == x + i; // assume(false); // } // assert (z == x+y); // assert (i == y); // return z; // }
Dafny_tmp_tmpmvs2dmry_examples2.dfy
201
201
Dafny program: 201
// returns an index of the largest element of array 'a' in the range [0..n) method findMax (a : array<int>, n : int) returns (r:int) requires a.Length > 0 requires 0 < n <= a.Length ensures 0 <= r < n <= a.Length; ensures forall k :: 0 <= k < n <= a.Length ==> a[r] >= a[k]; ensures multiset(a[..]) == multiset(old(a[..])); { var mi; var i; mi := 0; i := 0; while (i < n) { if (a[i] > a[mi]) { mi := i; } i := i + 1; } return mi; }
// returns an index of the largest element of array 'a' in the range [0..n) method findMax (a : array<int>, n : int) returns (r:int) requires a.Length > 0 requires 0 < n <= a.Length ensures 0 <= r < n <= a.Length; ensures forall k :: 0 <= k < n <= a.Length ==> a[r] >= a[k]; ensures multiset(a[..]) == multiset(old(a[..])); { var mi; var i; mi := 0; i := 0; while (i < n) invariant 0 <= i <= n <= a.Length; invariant 0 <= mi < n; invariant forall k :: 0 <= k < i ==> a[mi] >= a[k]; decreases n-i; { if (a[i] > a[mi]) { mi := i; } i := i + 1; } return mi; }
Dafny_tmp_tmpmvs2dmry_pancakesort_findmax.dfy
202
202
Dafny program: 202
// flips (i.e., reverses) array elements in the range [0..num] method flip (a: array<int>, num: int) requires a.Length > 0; requires 0 <= num < a.Length; modifies a; ensures forall k :: 0 <= k <= num ==> a[k] == old(a[num-k]) ensures forall k :: num < k < a.Length ==> a[k] == old(a[k]) // ensures multiset(a[..]) == old(multiset(a[..])) { var tmp:int; var i := 0; var j := num; while (i < j) // invariant 0 <= i < j <= num { tmp := a[i]; a[i] := a[j]; a[j] := tmp; i := i + 1; j := j - 1; } }
// flips (i.e., reverses) array elements in the range [0..num] method flip (a: array<int>, num: int) requires a.Length > 0; requires 0 <= num < a.Length; modifies a; ensures forall k :: 0 <= k <= num ==> a[k] == old(a[num-k]) ensures forall k :: num < k < a.Length ==> a[k] == old(a[k]) // ensures multiset(a[..]) == old(multiset(a[..])) { var tmp:int; var i := 0; var j := num; while (i < j) decreases j // invariant 0 <= i < j <= num invariant i + j == num invariant 0 <= i <= num/2+1 invariant num/2 <= j <= num invariant forall n :: 0 <= n < i ==> a[n] == old(a[num-n]) invariant forall n :: 0 <= n < i ==> a[num-n]==old(a[n]) invariant forall k :: i <= k <= j ==> a[k] == old(a[k]) invariant forall k :: num < k < a.Length ==> a[k] == old(a[k]) { tmp := a[i]; a[i] := a[j]; a[j] := tmp; i := i + 1; j := j - 1; } }
Dafny_tmp_tmpmvs2dmry_pancakesort_flip.dfy
203
203
Dafny program: 203
function min(a: int, b: int): int ensures min(a, b) <= a && min(a, b) <= b ensures min(a, b) == a || min(a, b) == b { if a < b then a else b } method minMethod(a: int, b: int) returns (c: int) ensures c <= a && c <= b ensures c == a || c == b // Ou encore: ensures c == min(a, b) { if a < b { c := a; } else { c := b; } } ghost function minFunction(a: int, b: int): int ensures minFunction(a, b) <= a && minFunction(a, b) <= b ensures minFunction(a, b) == a || minFunction(a, b) == b { if a < b then a else b } // Return a minimum of a. method minArray(a: array<int>) returns (m: int) requires a!= null && a.Length > 0 ; ensures forall k | 0 <= k < a.Length :: m <= a[k] ensures exists k | 0 <= k < a.Length :: m == a[k] { /* TODO */ m := a[0]; // Initialise m avec le premier élément du tableau var i := 1; while i < a.Length { /* TODO */ if a[i] < m { m := a[i]; } i := i + 1; } } method Main(){ var integer:= min(1,2); print(integer); }
function min(a: int, b: int): int ensures min(a, b) <= a && min(a, b) <= b ensures min(a, b) == a || min(a, b) == b { if a < b then a else b } method minMethod(a: int, b: int) returns (c: int) ensures c <= a && c <= b ensures c == a || c == b // Ou encore: ensures c == min(a, b) { if a < b { c := a; } else { c := b; } } ghost function minFunction(a: int, b: int): int ensures minFunction(a, b) <= a && minFunction(a, b) <= b ensures minFunction(a, b) == a || minFunction(a, b) == b { if a < b then a else b } // Return a minimum of a. method minArray(a: array<int>) returns (m: int) requires a!= null && a.Length > 0 ; ensures forall k | 0 <= k < a.Length :: m <= a[k] ensures exists k | 0 <= k < a.Length :: m == a[k] { /* TODO */ m := a[0]; // Initialise m avec le premier élément du tableau var i := 1; while i < a.Length invariant 0 <= i <= a.Length invariant forall k | 0 <= k < i :: m <= a[k] invariant exists k | 0 <= k < i :: m == a[k] { /* TODO */ if a[i] < m { m := a[i]; } i := i + 1; } } method Main(){ var integer:= min(1,2); print(integer); }
Dafny_tmp_tmpv_d3qi10_2_min.dfy
204
204
Dafny program: 204
function sum(a: array<int>, i: int): int requires 0 <= i < a.Length reads a { a[i] + if i == 0 then 0 else sum(a, i - 1) } method cumsum(a: array<int>, b: array<int>) requires a.Length == b.Length && a.Length > 0 && a != b // when you change a , that's not the same object than b . //requires b.Length > 0 ensures forall i | 0 <= i < a.Length :: b[i] == sum(a, i) modifies b { b[0] := a[0]; // Initialise le premier élément de b var i := 1; while i < a.Length { b[i] := b[i - 1] + a[i]; // Calcule la somme cumulée pour chaque élément i := i + 1; } }
function sum(a: array<int>, i: int): int requires 0 <= i < a.Length reads a { a[i] + if i == 0 then 0 else sum(a, i - 1) } method cumsum(a: array<int>, b: array<int>) requires a.Length == b.Length && a.Length > 0 && a != b // when you change a , that's not the same object than b . //requires b.Length > 0 ensures forall i | 0 <= i < a.Length :: b[i] == sum(a, i) modifies b { b[0] := a[0]; // Initialise le premier élément de b var i := 1; while i < a.Length invariant 1 <= i <= a.Length invariant forall i' | 0 <= i' < i :: b[i'] == sum(a, i') { b[i] := b[i - 1] + a[i]; // Calcule la somme cumulée pour chaque élément i := i + 1; } }
Dafny_tmp_tmpv_d3qi10_3_cumsum.dfy
205
205
Dafny program: 205
predicate IsOdd(x: int) { x % 2 == 1 } newtype Odd = n : int | IsOdd(n) witness 3 trait OddListSpec { var s: seq<Odd> var capacity: nat predicate Valid() reads this { 0 <= |s| <= this.capacity && forall i :: 0 <= i < |s| ==> IsOdd(s[i] as int) } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |s| method at(index: nat) returns (x: Odd) requires 0 <= index < |s| method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| } class OddList extends OddListSpec { constructor (capacity: nat) ensures Valid() ensures |s| == 0 ensures this.capacity == capacity { s := []; this.capacity := capacity; } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() { var tail := s[index..]; s := s[..index] + [element]; s := s + tail; } method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() { insert(0, element); } method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() { insert(|s|, element); } method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: int := 0 to |s| { if s[i] == element { s := s[..i] + s[i + 1..]; break; } } } method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { s := s[..index] + s[index + 1..]; } method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[0]; s := s[1..]; } method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[|s| - 1]; s := s[..|s| - 1]; } method length() returns (n: nat) ensures n == |s| { return |s|; } method at(index: nat) returns (x: Odd) requires 0 <= index < |s| ensures s[index] == x { return s[index]; } method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] { var left, right := 0, |s|; while left < right { var mid := (left + right) / 2; if element < s[mid] { right := mid; } else if s[mid] < element { left := mid + 1; } else { return mid; } } return -1; } method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| { l := new OddList(this.capacity + l2.capacity); var i, j := 0, 0; while i < |s| || j < |l2.s| { if i == |s| { if j == |l2.s| { return l; } else { l.pushBack(l2.s[j]); j := j + 1; } } else { if j == |l2.s| { l.pushBack(s[i]); i := i + 1; } else { if s[i] < l2.s[j] { l.pushBack(s[i]); i := i + 1; } else { l.pushBack(l2.s[j]); j := j + 1; } } } } return l; } } trait CircularLinkedListSpec<T(==)> { var l: seq<T> var capacity: nat predicate Valid() reads this { 0 <= |l| <= this.capacity } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |l| method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] } class CircularLinkedList<T(==)> extends CircularLinkedListSpec<T> { constructor (capacity: nat) requires capacity >= 0 ensures Valid() ensures |l| == 0 ensures this.capacity == capacity { l := []; this.capacity := capacity; } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() { if (|l| == 0) { l := [element]; } else { var actualIndex := index % |l|; var tail := l[actualIndex..]; l := l[..actualIndex] + [element]; l := l + tail; } } method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: nat := 0 to |l| { if l[i] == element { l := l[..i] + l[i + 1..]; break; } } } method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { var actualIndex := index % |l|; l := l[..actualIndex] + l[actualIndex + 1..]; } method length() returns (n: nat) ensures n == |l| { return |l|; } method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x { var actualIndex := index % |l|; return l[actualIndex]; } method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] { if (|l| == 1) { x := l[0]; } else { var actualIndex := index % |l|; if (actualIndex == (|l| - 1)) { x := l[0]; } else { x := l[actualIndex + 1]; } } return x; } method isIn(element: T) returns (b: bool) ensures |l| == 0 ==> b == false ensures |l| > 0 && b == true ==> exists i :: 0 <= i < |l| && l[i] == element ensures |l| > 0 && b == false ==> !exists i :: 0 <= i < |l| && l[i] == element { if (|l| == 0) { b := false; } else { b := false; for i: nat := 0 to |l| { if l[i] == element { b := true; break; } } } } }
predicate IsOdd(x: int) { x % 2 == 1 } newtype Odd = n : int | IsOdd(n) witness 3 trait OddListSpec { var s: seq<Odd> var capacity: nat predicate Valid() reads this { 0 <= |s| <= this.capacity && forall i :: 0 <= i < |s| ==> IsOdd(s[i] as int) } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |s| method at(index: nat) returns (x: Odd) requires 0 <= index < |s| method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| } class OddList extends OddListSpec { constructor (capacity: nat) ensures Valid() ensures |s| == 0 ensures this.capacity == capacity { s := []; this.capacity := capacity; } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() { var tail := s[index..]; s := s[..index] + [element]; s := s + tail; } method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() { insert(0, element); } method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() { insert(|s|, element); } method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: int := 0 to |s| invariant 0 <= i <= |s| invariant forall k :: 0 <= k < i ==> s[k] != element { if s[i] == element { s := s[..i] + s[i + 1..]; break; } } } method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { s := s[..index] + s[index + 1..]; } method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[0]; s := s[1..]; } method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[|s| - 1]; s := s[..|s| - 1]; } method length() returns (n: nat) ensures n == |s| { return |s|; } method at(index: nat) returns (x: Odd) requires 0 <= index < |s| ensures s[index] == x { return s[index]; } method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] { var left, right := 0, |s|; while left < right invariant 0 <= left <= right <= |s| invariant element !in s[..left] && element !in s[right..] { var mid := (left + right) / 2; if element < s[mid] { right := mid; } else if s[mid] < element { left := mid + 1; } else { return mid; } } return -1; } method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| { l := new OddList(this.capacity + l2.capacity); var i, j := 0, 0; while i < |s| || j < |l2.s| invariant 0 <= i <= |s| invariant 0 <= j <= |l2.s| invariant i + j == |l.s| invariant |l.s| <= l.capacity invariant l.capacity == this.capacity + l2.capacity decreases |s| - i, |l2.s| - j { if i == |s| { if j == |l2.s| { return l; } else { l.pushBack(l2.s[j]); j := j + 1; } } else { if j == |l2.s| { l.pushBack(s[i]); i := i + 1; } else { if s[i] < l2.s[j] { l.pushBack(s[i]); i := i + 1; } else { l.pushBack(l2.s[j]); j := j + 1; } } } } return l; } } trait CircularLinkedListSpec<T(==)> { var l: seq<T> var capacity: nat predicate Valid() reads this { 0 <= |l| <= this.capacity } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |l| method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] } class CircularLinkedList<T(==)> extends CircularLinkedListSpec<T> { constructor (capacity: nat) requires capacity >= 0 ensures Valid() ensures |l| == 0 ensures this.capacity == capacity { l := []; this.capacity := capacity; } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() { if (|l| == 0) { l := [element]; } else { var actualIndex := index % |l|; var tail := l[actualIndex..]; l := l[..actualIndex] + [element]; l := l + tail; } } method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: nat := 0 to |l| invariant 0 <= i <= |l| invariant forall k :: 0 <= k < i ==> l[k] != element { if l[i] == element { l := l[..i] + l[i + 1..]; break; } } } method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { var actualIndex := index % |l|; l := l[..actualIndex] + l[actualIndex + 1..]; } method length() returns (n: nat) ensures n == |l| { return |l|; } method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x { var actualIndex := index % |l|; return l[actualIndex]; } method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] { if (|l| == 1) { x := l[0]; } else { var actualIndex := index % |l|; if (actualIndex == (|l| - 1)) { x := l[0]; } else { x := l[actualIndex + 1]; } } return x; } method isIn(element: T) returns (b: bool) ensures |l| == 0 ==> b == false ensures |l| > 0 && b == true ==> exists i :: 0 <= i < |l| && l[i] == element ensures |l| > 0 && b == false ==> !exists i :: 0 <= i < |l| && l[i] == element { if (|l| == 0) { b := false; } else { b := false; for i: nat := 0 to |l| invariant 0 <= i <= |l| invariant forall k :: 0 <= k < i ==> l[k] != element { if l[i] == element { b := true; break; } } } } }
FMSE-2022-2023_tmp_tmp6_x_ba46_Lab10_Lab10.dfy
207
207
Dafny program: 207
/* * Task 2: Define the natural numbers as an algebraic data type * * Being an inductive data type, it's required that we have a base case constructor and an inductive one. */ datatype Nat = Zero | S(Pred: Nat) /// Task 2 // Exercise (a'): proving that the successor constructor is injective /* * It's known that the successors are equal. * It's know that for equal inputs, a non-random function returns the same result. * Thus, the predecessors of the successors, namely, the numbers themselves, are equal. */ lemma SIsInjective(x: Nat, y: Nat) ensures S(x) == S(y) ==> x == y { assume S(x) == S(y); } // Exercise (a''): Zero is different from successor(x), for any x /* * For all x: Nat, S(x) is built using the S constructor, implying that S(x).Zero? is inherently false. */ lemma ZeroIsDifferentFromSuccessor(n: Nat) ensures S(n) != Zero { } // Exercise (b): inductively defining the addition of natural numbers /* * The function decreases y until it reaches the base inductive case. * The Addition between Zero and a x: Nat will be x. * The Addition between a successor of a y': Nat and another x: Nat is the successor of the Addition between y' and x * * x + y = 1 + ((x - 1) + y) */ function Add(x: Nat, y: Nat) : Nat { match y case Zero => x case S(y') => S(Add(x, y')) } // Exercise (c'): proving that the addition is commutative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Neutral. */ lemma {:induction n} ZeroAddNeutral(n: Nat) ensures Add(n, Zero) == Add(Zero, n) == n { match n case Zero => { == Add(Zero, Zero) == Add(Zero, n) == n; } case S(n') => { == Add(S(n'), Zero) == S(n') == Add(Zero, S(n')) == Add(Zero, n) == n; } } /* * Since Zero is neutral, it is trivial that the order of addition is not of importance. */ lemma {:induction n} ZeroAddCommutative(n: Nat) ensures Add(Zero, n) == Add(n, Zero) { == n == Add(n, Zero); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddCommutative(x: Nat, y: Nat) ensures Add(x, y) == Add(y, x) { match x case Zero => ZeroAddCommutative(y); case S(x') => AddCommutative(x', y); } // Exercise (c''): proving that the addition is associative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Associative. * * Again, given that addition with Zero is neutral, the order of calculations is irrelevant. */ lemma {:induction x, y} ZeroAddAssociative(x: Nat, y: Nat) ensures Add(Add(Zero, x), y) == Add(Zero, Add(x, y)) { ZeroAddNeutral(x); == // ZeroAddNeutral Add(x, y) == Add(Zero, Add(x, y)); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddAssociative(x: Nat, y: Nat, z: Nat) ensures Add(Add(x, y), z) == Add(x, Add(y, z)) { match z case Zero => ZeroAddAssociative(Add(x, y), Zero); case S(z') => AddAssociative(x, y, z'); } // Exercise (d): defining a predicate lt(m, n) that holds when m is less than n /* * If x is Zero and y is a Successor, given that we have proven ZeroIsDifferentFromSuccessor for all x, the predicate holds. * Otherwise, if both are successors, we inductively check their predecessors. */ predicate LessThan(x: Nat, y: Nat) { (x.Zero? && y.S?) || (x.S? && y.S? && LessThan(x.Pred, y.Pred)) } // Exercise (e): proving that lt is transitive /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that LessThan is Transitive having a Zero as the left-most parameter. * * We prove this statement using Reductio Ad Absurdum. * We suppose that Zero is not smaller that an arbitrary z that is non-Zero. * This would imply that Zero has to be a Successor (i.e. Zero.S? == true). * This is inherently false. */ lemma {:induction y, z} LessThanIsTransitiveWithZero(y: Nat, z: Nat) requires LessThan(Zero, y) requires LessThan(y, z) ensures LessThan(Zero, z) { if !LessThan(Zero, z) { } } /* * Since now the base case of transitive LessThan with Zero is proven, we can now prove using induction. * * In this case, the induction decreases on all three variables, all x, y, z until the base case. */ lemma {:induction x, y, z} LessThanIsTransitive(x: Nat, y: Nat, z: Nat) requires LessThan(x, y) requires LessThan(y, z) ensures LessThan(x, z) { match x case Zero => LessThanIsTransitiveWithZero(y, z); case S(x') => match y case S(y') => match z case S(z') => LessThanIsTransitive(x', y', z'); } /// Task 3: Define the parametric lists as an algebraic data type /* * Being an inductive data type, it's required that we have a base case constructor and an inductive one. * The inductive Append constructor takes as input a Nat, the head, and a tail, the rest of the list. */ datatype List<T> = Nil | Append(head: T, tail: List) // Exercise (a): defining the size of a list (using natural numbers defined above) /* * We are modelling the function as a recursive one. * The size of an empty list (Nil) is Zero. * * The size of a non-empty list is the successor of the size of the list's tail. */ function Size(l: List<Nat>): Nat { if l.Nil? then Zero else S(Size(l.tail)) } // Exercise (b): defining the concatenation of two lists /* * Concatenation with an empty list yields the other list. * * The function recursively calculates the result of the concatenation. */ function Concatenation(l1: List<Nat>, l2: List<Nat>) : List<Nat> { match l1 case Nil => l2 case Append(head1, tail1) => match l2 case Nil => l1 case Append(_, _) => Append(head1, Concatenation(tail1, l2)) } // Exercise (c): proving that the size of the concatenation of two lists is the sum of the lists' sizes /* * Starting with a base case in which the first list is empty, the proof is trivial, given ZeroAddNeutral. * Afterwards, the induction follows the next step and matches the second list. * If the list is empty, the result will be, of course, the first list. * Otherwise, an element is discarded from both (the heads), and the verification continues on the tails. */ lemma {:induction l1, l2} SizeOfConcatenationIsSumOfSizes(l1: List<Nat>, l2: List<Nat>) ensures Size(Concatenation(l1, l2)) == Add(Size(l1), Size(l2)) { match l1 case Nil => { ZeroAddNeutral(Size(l2)); == Size(Concatenation(Nil, l2)) == Size(l2) == // ZeroAddNeutral Add(Zero, Size(l2)) == Add(Size(l1), Size(l2)); } case Append(_, tail1) => match l2 case Nil => { == Size(Concatenation(l1, Nil)) == Size(l1) == Add(Size(l1), Zero) == Add(Size(l1), Size(l2)); } case Append(_, tail2) => SizeOfConcatenationIsSumOfSizes(tail1, tail2); } // Exercise (d): defining a function reversing a list /* * The base case is, again, the empty list. * When the list is empty, the reverse of the list is also Nil. * * When dealing with a non-empty list, we make use of the Concatenation operation. * The Reverse of the list will be a concatenation between the reverse of the tail and the head. * Since the head is not a list on its own, a list is created using the Append constructor. */ function ReverseList(l: List<Nat>) : List<Nat> { if l.Nil? then Nil else Concatenation(ReverseList(l.tail), Append(l.head, Nil)) } // Exercise (e): proving that reversing a list twice we obtain the initial list. /* * Given that during the induction we need to make use of this property, * we first save the result of reversing a concatenation between a list and a single element. * * Aside from the base case, proven with chained equality assertions, the proof follows an inductive approach as well. */ lemma {:induction l, n} ReversalOfConcatenationWithHead(l: List<Nat>, n: Nat) ensures ReverseList(Concatenation(l, Append(n, Nil))) == Append(n, ReverseList(l)) { match l case Nil => { == ReverseList(Concatenation(Nil, Append(n, Nil))) == ReverseList(Append(n, Nil)) == Concatenation(ReverseList(Append(n, Nil).tail), Append(Append(n, Nil).head, Nil)) == Concatenation(ReverseList(Nil), Append(n, Nil)) == Concatenation(Nil, Append(n, Nil)) == Append(n, Nil) == Append(n, l) == Append(n, ReverseList(l)); } case Append(head, tail) => ReversalOfConcatenationWithHead(tail, n); } /* * The induction starts with the base case, which is trivial. * * For the inductive steps, there is a need for the property proven above. * Once the property is guaranteed, the chained assertions lead to the solution. */ lemma {:induction l} DoubleReversalResultsInInitialList(l: List<Nat>) ensures l == ReverseList(ReverseList(l)) { match l case Nil => { == ReverseList(ReverseList(Nil)) == ReverseList(Nil) == Nil; } case Append(head, tail) => { ReversalOfConcatenationWithHead(ReverseList(tail), head); == ReverseList(ReverseList(Append(head, tail))) == ReverseList(Concatenation(ReverseList(tail), Append(head, Nil))) == // ReversalOfConcatenationWithHead Append(head, ReverseList(ReverseList(tail))) == Append(head, tail) == l; } }
/* * Task 2: Define the natural numbers as an algebraic data type * * Being an inductive data type, it's required that we have a base case constructor and an inductive one. */ datatype Nat = Zero | S(Pred: Nat) /// Task 2 // Exercise (a'): proving that the successor constructor is injective /* * It's known that the successors are equal. * It's know that for equal inputs, a non-random function returns the same result. * Thus, the predecessors of the successors, namely, the numbers themselves, are equal. */ lemma SIsInjective(x: Nat, y: Nat) ensures S(x) == S(y) ==> x == y { assume S(x) == S(y); assert S(x).Pred == S(y).Pred; assert x == y; } // Exercise (a''): Zero is different from successor(x), for any x /* * For all x: Nat, S(x) is built using the S constructor, implying that S(x).Zero? is inherently false. */ lemma ZeroIsDifferentFromSuccessor(n: Nat) ensures S(n) != Zero { assert S(n).Zero? == false; } // Exercise (b): inductively defining the addition of natural numbers /* * The function decreases y until it reaches the base inductive case. * The Addition between Zero and a x: Nat will be x. * The Addition between a successor of a y': Nat and another x: Nat is the successor of the Addition between y' and x * * x + y = 1 + ((x - 1) + y) */ function Add(x: Nat, y: Nat) : Nat decreases y { match y case Zero => x case S(y') => S(Add(x, y')) } // Exercise (c'): proving that the addition is commutative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Neutral. */ lemma {:induction n} ZeroAddNeutral(n: Nat) ensures Add(n, Zero) == Add(Zero, n) == n { match n case Zero => { assert Add(n, Zero) == Add(Zero, Zero) == Add(Zero, n) == n; } case S(n') => { assert Add(n, Zero) == Add(S(n'), Zero) == S(n') == Add(Zero, S(n')) == Add(Zero, n) == n; } } /* * Since Zero is neutral, it is trivial that the order of addition is not of importance. */ lemma {:induction n} ZeroAddCommutative(n: Nat) ensures Add(Zero, n) == Add(n, Zero) { assert Add(Zero, n) == n == Add(n, Zero); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddCommutative(x: Nat, y: Nat) ensures Add(x, y) == Add(y, x) decreases x, y { match x case Zero => ZeroAddCommutative(y); case S(x') => AddCommutative(x', y); } // Exercise (c''): proving that the addition is associative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Associative. * * Again, given that addition with Zero is neutral, the order of calculations is irrelevant. */ lemma {:induction x, y} ZeroAddAssociative(x: Nat, y: Nat) ensures Add(Add(Zero, x), y) == Add(Zero, Add(x, y)) { ZeroAddNeutral(x); assert Add(Add(Zero, x), y) == // ZeroAddNeutral Add(x, y) == Add(Zero, Add(x, y)); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddAssociative(x: Nat, y: Nat, z: Nat) ensures Add(Add(x, y), z) == Add(x, Add(y, z)) decreases z { match z case Zero => ZeroAddAssociative(Add(x, y), Zero); case S(z') => AddAssociative(x, y, z'); } // Exercise (d): defining a predicate lt(m, n) that holds when m is less than n /* * If x is Zero and y is a Successor, given that we have proven ZeroIsDifferentFromSuccessor for all x, the predicate holds. * Otherwise, if both are successors, we inductively check their predecessors. */ predicate LessThan(x: Nat, y: Nat) decreases x, y { (x.Zero? && y.S?) || (x.S? && y.S? && LessThan(x.Pred, y.Pred)) } // Exercise (e): proving that lt is transitive /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that LessThan is Transitive having a Zero as the left-most parameter. * * We prove this statement using Reductio Ad Absurdum. * We suppose that Zero is not smaller that an arbitrary z that is non-Zero. * This would imply that Zero has to be a Successor (i.e. Zero.S? == true). * This is inherently false. */ lemma {:induction y, z} LessThanIsTransitiveWithZero(y: Nat, z: Nat) requires LessThan(Zero, y) requires LessThan(y, z) ensures LessThan(Zero, z) { if !LessThan(Zero, z) { assert z != Zero; assert Zero.S?; assert false; } } /* * Since now the base case of transitive LessThan with Zero is proven, we can now prove using induction. * * In this case, the induction decreases on all three variables, all x, y, z until the base case. */ lemma {:induction x, y, z} LessThanIsTransitive(x: Nat, y: Nat, z: Nat) requires LessThan(x, y) requires LessThan(y, z) ensures LessThan(x, z) decreases x { match x case Zero => LessThanIsTransitiveWithZero(y, z); case S(x') => match y case S(y') => match z case S(z') => LessThanIsTransitive(x', y', z'); } /// Task 3: Define the parametric lists as an algebraic data type /* * Being an inductive data type, it's required that we have a base case constructor and an inductive one. * The inductive Append constructor takes as input a Nat, the head, and a tail, the rest of the list. */ datatype List<T> = Nil | Append(head: T, tail: List) // Exercise (a): defining the size of a list (using natural numbers defined above) /* * We are modelling the function as a recursive one. * The size of an empty list (Nil) is Zero. * * The size of a non-empty list is the successor of the size of the list's tail. */ function Size(l: List<Nat>): Nat decreases l { if l.Nil? then Zero else S(Size(l.tail)) } // Exercise (b): defining the concatenation of two lists /* * Concatenation with an empty list yields the other list. * * The function recursively calculates the result of the concatenation. */ function Concatenation(l1: List<Nat>, l2: List<Nat>) : List<Nat> decreases l1, l2 { match l1 case Nil => l2 case Append(head1, tail1) => match l2 case Nil => l1 case Append(_, _) => Append(head1, Concatenation(tail1, l2)) } // Exercise (c): proving that the size of the concatenation of two lists is the sum of the lists' sizes /* * Starting with a base case in which the first list is empty, the proof is trivial, given ZeroAddNeutral. * Afterwards, the induction follows the next step and matches the second list. * If the list is empty, the result will be, of course, the first list. * Otherwise, an element is discarded from both (the heads), and the verification continues on the tails. */ lemma {:induction l1, l2} SizeOfConcatenationIsSumOfSizes(l1: List<Nat>, l2: List<Nat>) ensures Size(Concatenation(l1, l2)) == Add(Size(l1), Size(l2)) decreases l1, l2 { match l1 case Nil => { ZeroAddNeutral(Size(l2)); assert Size(Concatenation(l1, l2)) == Size(Concatenation(Nil, l2)) == Size(l2) == // ZeroAddNeutral Add(Zero, Size(l2)) == Add(Size(l1), Size(l2)); } case Append(_, tail1) => match l2 case Nil => { assert Size(Concatenation(l1, l2)) == Size(Concatenation(l1, Nil)) == Size(l1) == Add(Size(l1), Zero) == Add(Size(l1), Size(l2)); } case Append(_, tail2) => SizeOfConcatenationIsSumOfSizes(tail1, tail2); } // Exercise (d): defining a function reversing a list /* * The base case is, again, the empty list. * When the list is empty, the reverse of the list is also Nil. * * When dealing with a non-empty list, we make use of the Concatenation operation. * The Reverse of the list will be a concatenation between the reverse of the tail and the head. * Since the head is not a list on its own, a list is created using the Append constructor. */ function ReverseList(l: List<Nat>) : List<Nat> decreases l { if l.Nil? then Nil else Concatenation(ReverseList(l.tail), Append(l.head, Nil)) } // Exercise (e): proving that reversing a list twice we obtain the initial list. /* * Given that during the induction we need to make use of this property, * we first save the result of reversing a concatenation between a list and a single element. * * Aside from the base case, proven with chained equality assertions, the proof follows an inductive approach as well. */ lemma {:induction l, n} ReversalOfConcatenationWithHead(l: List<Nat>, n: Nat) ensures ReverseList(Concatenation(l, Append(n, Nil))) == Append(n, ReverseList(l)) decreases l, n { match l case Nil => { assert ReverseList(Concatenation(l, Append(n, Nil))) == ReverseList(Concatenation(Nil, Append(n, Nil))) == ReverseList(Append(n, Nil)) == Concatenation(ReverseList(Append(n, Nil).tail), Append(Append(n, Nil).head, Nil)) == Concatenation(ReverseList(Nil), Append(n, Nil)) == Concatenation(Nil, Append(n, Nil)) == Append(n, Nil) == Append(n, l) == Append(n, ReverseList(l)); } case Append(head, tail) => ReversalOfConcatenationWithHead(tail, n); } /* * The induction starts with the base case, which is trivial. * * For the inductive steps, there is a need for the property proven above. * Once the property is guaranteed, the chained assertions lead to the solution. */ lemma {:induction l} DoubleReversalResultsInInitialList(l: List<Nat>) ensures l == ReverseList(ReverseList(l)) { match l case Nil => { assert ReverseList(ReverseList(l)) == ReverseList(ReverseList(Nil)) == ReverseList(Nil) == Nil; assert l == ReverseList(ReverseList(l)); } case Append(head, tail) => { ReversalOfConcatenationWithHead(ReverseList(tail), head); assert ReverseList(ReverseList(l)) == ReverseList(ReverseList(Append(head, tail))) == ReverseList(Concatenation(ReverseList(tail), Append(head, Nil))) == // ReversalOfConcatenationWithHead Append(head, ReverseList(ReverseList(tail))) == Append(head, tail) == l; } }
FMSE-2022-2023_tmp_tmp6_x_ba46_Lab2_Lab2.dfy
208
208
Dafny program: 208
/* * Task 2: Define in Dafny the conatural numbers as a coinductive datatype * * Being a coinductive data type, it's required that we have a base case constructor and an inductive one * (as is the case with inductive ones as well) */ codatatype Conat = Zero | Succ(Pred: Conat) // Exercise (a): explain why the following coinductive property does NOT hold // lemma ConstructorConat(n: Conat) // ensures n != Succ(n) // { // the following coinductive property does not hold because coinductive datatypes, as opposed to normal datatypes, // are designed for infinite domains, as such, it is improper to test the equality above when dealing with infinity // } // Exercise (b): show that the constructor successor is injective greatest lemma ConstructorInjective(x: Conat, y: Conat) ensures Succ(x) == Succ(y) ==> x == y { assume Succ(x) == Succ(y); } // Exercise (c): define the ∞ constant (as a corecursive function) // We use a co-recursive call using the Succ constructor on the result, producing an infinite call stack function inf(n: Conat): Conat { Succ(inf(n)) } // Exercise (d): define the addition of conaturals // Similar to add function over the Nat datatype (See Lab2) function add(x: Conat, y: Conat) : Conat { match x case Zero => y case Succ(x') => Succ(add(x', y)) } // Exercise (e): show that by adding ∞ to itself it remains unchanged // Because the focus is on greatest fixed-point we need to use a co-predicate // Aptly renamed to greatest predicate greatest predicate InfinityAddition() { add(inf(Zero), inf(Zero)) == inf(Zero) } // Task 3: Define the parametric streams as a coinductive datatype where s ranges over streams codatatype Stream<A> = Cons(head: A, tail: Stream<A>) // Exercise (a): corecursively define the pointwise addition of two streams of integers // After performing the addition of the value in the heads, proceed similarly with the tails function addition(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head + b.head, addition(a.tail, b.tail)) } // Exercise (b): define a parametric integer constant stream // An infinite stream with the same value function cnst(a: int): Stream<int> { Cons(a, cnst(a)) } // Exercise (c): prove by coinduction that add(s, cnst(0)) = s; // The proof tried below is not complete, however, by telling Dafny that we are dealing with a colemma, // Aptly renamed to greatest lemma, it is able to reason and prove the post-condition by itself greatest lemma additionWithZero(a : Stream<int>) ensures addition(a, cnst(0)) == a { // assert addition(a, cnst(0)) // == // Cons(a.head + cnst(0).head, addition(a.tail, cnst(0).tail)) // == // Cons(a.head + 0, addition(a.tail, cnst(0))) // == // Cons(a.head, addition(a.tail, cnst(0))) // == // Cons(a.head, a.tail) // == // a; } // Exercise (d): define coinductively the predicate greatest predicate leq(a: Stream<int>, b: Stream<int>) { a.head <= b.head && ((a.head == b.head) ==> leq(a.tail, b.tail)) } // Exercise (e): (e) define the stream blink function blink(): Stream<int> { Cons(0, Cons(1, blink())) } // Exercise (f): prove by coinduction that leq(cnst(0), blink) lemma CnstZeroLeqBlink() ensures leq(cnst(0), blink()) { } // Exercise (g): define a function that ”zips” two streams // A stream formed by alternating the elements of both streams one by one function zip(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head, Cons(b.head, zip(a.tail, b.tail))) } // Exercise (h): prove that zipping cnst(0) and cnst(1) yields blink // By using a greatest lemma, Dafny can reason on its own greatest lemma ZipCnstZeroCnstOneEqualsBlink() ensures zip(cnst(0), cnst(1)) == blink() { // assert zip(cnst(0), cnst(1)) // == // Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0), cnst(1)))) // == // Cons(0, Cons(1, Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0), cnst(1)))))) // == // blink(); }
/* * Task 2: Define in Dafny the conatural numbers as a coinductive datatype * * Being a coinductive data type, it's required that we have a base case constructor and an inductive one * (as is the case with inductive ones as well) */ codatatype Conat = Zero | Succ(Pred: Conat) // Exercise (a): explain why the following coinductive property does NOT hold // lemma ConstructorConat(n: Conat) // ensures n != Succ(n) // { // the following coinductive property does not hold because coinductive datatypes, as opposed to normal datatypes, // are designed for infinite domains, as such, it is improper to test the equality above when dealing with infinity // } // Exercise (b): show that the constructor successor is injective greatest lemma ConstructorInjective(x: Conat, y: Conat) ensures Succ(x) == Succ(y) ==> x == y { assume Succ(x) == Succ(y); assert Succ(x).Pred == Succ(y).Pred; assert x == y; } // Exercise (c): define the ∞ constant (as a corecursive function) // We use a co-recursive call using the Succ constructor on the result, producing an infinite call stack function inf(n: Conat): Conat { Succ(inf(n)) } // Exercise (d): define the addition of conaturals // Similar to add function over the Nat datatype (See Lab2) function add(x: Conat, y: Conat) : Conat { match x case Zero => y case Succ(x') => Succ(add(x', y)) } // Exercise (e): show that by adding ∞ to itself it remains unchanged // Because the focus is on greatest fixed-point we need to use a co-predicate // Aptly renamed to greatest predicate greatest predicate InfinityAddition() { add(inf(Zero), inf(Zero)) == inf(Zero) } // Task 3: Define the parametric streams as a coinductive datatype where s ranges over streams codatatype Stream<A> = Cons(head: A, tail: Stream<A>) // Exercise (a): corecursively define the pointwise addition of two streams of integers // After performing the addition of the value in the heads, proceed similarly with the tails function addition(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head + b.head, addition(a.tail, b.tail)) } // Exercise (b): define a parametric integer constant stream // An infinite stream with the same value function cnst(a: int): Stream<int> { Cons(a, cnst(a)) } // Exercise (c): prove by coinduction that add(s, cnst(0)) = s; // The proof tried below is not complete, however, by telling Dafny that we are dealing with a colemma, // Aptly renamed to greatest lemma, it is able to reason and prove the post-condition by itself greatest lemma additionWithZero(a : Stream<int>) ensures addition(a, cnst(0)) == a { // assert addition(a, cnst(0)) // == // Cons(a.head + cnst(0).head, addition(a.tail, cnst(0).tail)) // == // Cons(a.head + 0, addition(a.tail, cnst(0))) // == // Cons(a.head, addition(a.tail, cnst(0))) // == // Cons(a.head, a.tail) // == // a; } // Exercise (d): define coinductively the predicate greatest predicate leq(a: Stream<int>, b: Stream<int>) { a.head <= b.head && ((a.head == b.head) ==> leq(a.tail, b.tail)) } // Exercise (e): (e) define the stream blink function blink(): Stream<int> { Cons(0, Cons(1, blink())) } // Exercise (f): prove by coinduction that leq(cnst(0), blink) lemma CnstZeroLeqBlink() ensures leq(cnst(0), blink()) { } // Exercise (g): define a function that ”zips” two streams // A stream formed by alternating the elements of both streams one by one function zip(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head, Cons(b.head, zip(a.tail, b.tail))) } // Exercise (h): prove that zipping cnst(0) and cnst(1) yields blink // By using a greatest lemma, Dafny can reason on its own greatest lemma ZipCnstZeroCnstOneEqualsBlink() ensures zip(cnst(0), cnst(1)) == blink() { // assert zip(cnst(0), cnst(1)) // == // Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0), cnst(1)))) // == // Cons(0, Cons(1, Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0), cnst(1)))))) // == // blink(); }
FMSE-2022-2023_tmp_tmp6_x_ba46_Lab3_Lab3.dfy
209
209
Dafny program: 209
method incrementArray(a:array<int>) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1 modifies a { var j : int := 0; while(j < a.Length) { a[j] := a[j] + 1; j := j+1; } }
method incrementArray(a:array<int>) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1 modifies a { var j : int := 0; while(j < a.Length) invariant 0 <= j <= a.Length invariant forall i :: j <= i < a.Length ==> a[i] == old(a[i]) invariant forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1 decreases a.Length - j { assert forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1; assert a[j] == old(a[j]); a[j] := a[j] + 1; assert forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1; assert a[j] == old(a[j]) + 1; j := j+1; } }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise3_Increment_Array.dfy
210
210
Dafny program: 210
method findMax(a:array<int>) returns (pos:int, maxVal: int) requires a.Length > 0; requires forall i :: 0 <= i < a.Length ==> a[i] >= 0; ensures forall i :: 0 <= i < a.Length ==> a[i] <= maxVal; ensures exists i :: 0 <= i < a.Length && a[i] == maxVal; ensures 0 <= pos < a.Length ensures a[pos] == maxVal; { pos := 0; maxVal := a[0]; var j := 1; while(j < a.Length) { if (a[j] > maxVal) { maxVal := a[j]; pos := j; } j := j+1; } return; }
method findMax(a:array<int>) returns (pos:int, maxVal: int) requires a.Length > 0; requires forall i :: 0 <= i < a.Length ==> a[i] >= 0; ensures forall i :: 0 <= i < a.Length ==> a[i] <= maxVal; ensures exists i :: 0 <= i < a.Length && a[i] == maxVal; ensures 0 <= pos < a.Length ensures a[pos] == maxVal; { pos := 0; maxVal := a[0]; var j := 1; while(j < a.Length) invariant 1 <= j <= a.Length; invariant forall i :: 0 <= i < j ==> a[i] <= maxVal; invariant exists i :: 0 <= i < j && a[i] == maxVal; invariant 0 <= pos < a.Length; invariant a[pos] == maxVal; { if (a[j] > maxVal) { maxVal := a[j]; pos := j; } j := j+1; } return; }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise4_Find_Max.dfy
211
211
Dafny program: 211
method binarySearch(a:array<int>, val:int) returns (pos:int) requires a.Length > 0 requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures 0 <= pos < a.Length ==> a[pos] == val ensures pos < 0 || pos >= a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] != val { var left := 0; var right := a.Length; if a[left] > val || a[right-1] < val { return -1; } while left < right { var med := (left + right) / 2; if a[med] < val { left := med + 1; } else if a[med] > val { right := med; } else { pos := med; return; } } return -1; }
method binarySearch(a:array<int>, val:int) returns (pos:int) requires a.Length > 0 requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures 0 <= pos < a.Length ==> a[pos] == val ensures pos < 0 || pos >= a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] != val { var left := 0; var right := a.Length; if a[left] > val || a[right-1] < val { return -1; } while left < right invariant 0 <= left <= right <= a.Length invariant forall i :: 0 <= i < a.Length && !(left <= i < right) ==> a[i] != val decreases right - left { var med := (left + right) / 2; assert left <= med <= right; if a[med] < val { left := med + 1; } else if a[med] > val { right := med; } else { assert a[med] == val; pos := med; return; } } return -1; }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise6_Binary_Search.dfy
212
212
Dafny program: 212
predicate sorted (a: array<int>) reads a { sortedA(a, a.Length) } predicate sortedA (a: array<int>, i: int) requires 0 <= i <= a.Length reads a { forall k :: 0 < k < i ==> a[k-1] <= a[k] } method lookForMin (a: array<int>, i: int) returns (m: int) requires 0 <= i < a.Length ensures i <= m < a.Length ensures forall k :: i <= k < a.Length ==> a[k] >= a[m] { var j := i; m := i; while(j < a.Length) { if(a[j] < a[m]) { m := j; } j := j + 1; } } method insertionSort (a: array<int>) modifies a ensures sorted(a) { var c := 0; while(c < a.Length) { var m := lookForMin(a, c); a[m], a[c] := a[c], a[m]; c := c + 1; } }
predicate sorted (a: array<int>) reads a { sortedA(a, a.Length) } predicate sortedA (a: array<int>, i: int) requires 0 <= i <= a.Length reads a { forall k :: 0 < k < i ==> a[k-1] <= a[k] } method lookForMin (a: array<int>, i: int) returns (m: int) requires 0 <= i < a.Length ensures i <= m < a.Length ensures forall k :: i <= k < a.Length ==> a[k] >= a[m] { var j := i; m := i; while(j < a.Length) invariant i <= j <= a.Length invariant i <= m < a.Length invariant forall k :: i <= k < j ==> a[k] >= a[m] decreases a.Length - j { if(a[j] < a[m]) { m := j; } j := j + 1; } } method insertionSort (a: array<int>) modifies a ensures sorted(a) { var c := 0; while(c < a.Length) invariant 0 <= c <= a.Length invariant forall k, l :: 0 <= k < c <= l < a.Length ==> a[k] <= a[l] invariant sortedA(a, c) { var m := lookForMin(a, c); a[m], a[c] := a[c], a[m]; assert forall k :: c <= k < a.Length ==> a[k] >= a[c]; c := c + 1; } }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Insertion_Sort_Normal.dfy
213
213
Dafny program: 213
predicate InsertionSorted(Array: array<int>, left: int, right: int) requires 0 <= left <= right <= Array.Length reads Array { forall i,j :: left <= i < j < right ==> Array[i] <= Array[j] } method sorting(Array: array<int>) requires Array.Length > 1 ensures InsertionSorted(Array, 0, Array.Length) modifies Array { var high := 1; while (high < Array.Length) { var low := high-1; while low >= 0 && Array[low+1] < Array[low] { Array[low], Array[low+1] := Array[low+1], Array[low]; low := low-1; } high := high+1; } }
predicate InsertionSorted(Array: array<int>, left: int, right: int) requires 0 <= left <= right <= Array.Length reads Array { forall i,j :: left <= i < j < right ==> Array[i] <= Array[j] } method sorting(Array: array<int>) requires Array.Length > 1 ensures InsertionSorted(Array, 0, Array.Length) modifies Array { var high := 1; while (high < Array.Length) invariant 1 <= high <= Array.Length invariant InsertionSorted(Array,0,high) { var low := high-1; while low >= 0 && Array[low+1] < Array[low] invariant forall idx,idx' :: 0 <= idx < idx' < high+1 && idx' != low+1 ==> Array[idx] <= Array[idx'] { Array[low], Array[low+1] := Array[low+1], Array[low]; low := low-1; } high := high+1; } }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Insertion_Sorted_Standard.dfy
214
214
Dafny program: 214
method mergeSort(a: array<int>) modifies a { sorting(a, 0, a.Length-1); } method merging(a: array<int>, low: int, medium: int, high: int) requires 0 <= low <= medium <= high < a.Length modifies a { var x := 0; var y := 0; var z := 0; var a1: array<int> := new [medium - low + 1]; var a2: array<int> := new [high - medium]; // The first case while(y < a1.Length && low+y < a.Length) { a1[y] := a[low+y]; y := y +1; } // The second case while(z < a2.Length && medium+z+1 < a.Length) { a2[z] := a[medium+z+1]; z := z +1; } y, z := 0, 0; // The third case while (x < high - low + 1 && y <= a1.Length && z <= a2.Length && low+x < a.Length) { if(y >= a1.Length && z >= a2.Length) { break; } else if(y >= a1.Length) { a[low+x] := a2[z]; z := z+1; } else if(z >= a2.Length) { a[low+x] := a1[y]; y := y+1; } else { if(a1[y] <= a2[z]) { a[low+x] := a1[y]; y := y +1; } else { a[low+x] := a2[z]; z := z +1; } } x := x+1; } } method sorting(a: array<int>, low: int, high: int) requires 0 <= low && high < a.Length modifies a { if (low < high) { var medium: int := low + (high - low)/2; sorting(a, low, medium); sorting(a, medium+1, high); merging(a, low, medium, high); } }
method mergeSort(a: array<int>) modifies a { sorting(a, 0, a.Length-1); } method merging(a: array<int>, low: int, medium: int, high: int) requires 0 <= low <= medium <= high < a.Length modifies a { var x := 0; var y := 0; var z := 0; var a1: array<int> := new [medium - low + 1]; var a2: array<int> := new [high - medium]; // The first case while(y < a1.Length && low+y < a.Length) invariant 0 <= y <= a1.Length invariant 0 <= low+y <= a.Length decreases a1.Length-y { a1[y] := a[low+y]; y := y +1; } // The second case while(z < a2.Length && medium+z+1 < a.Length) invariant 0 <= z <= a2.Length invariant 0 <= medium+z <= a.Length decreases a2.Length-z { a2[z] := a[medium+z+1]; z := z +1; } y, z := 0, 0; // The third case while (x < high - low + 1 && y <= a1.Length && z <= a2.Length && low+x < a.Length) invariant 0 <= x <= high - low + 1 decreases high-low-x { if(y >= a1.Length && z >= a2.Length) { break; } else if(y >= a1.Length) { a[low+x] := a2[z]; z := z+1; } else if(z >= a2.Length) { a[low+x] := a1[y]; y := y+1; } else { if(a1[y] <= a2[z]) { a[low+x] := a1[y]; y := y +1; } else { a[low+x] := a2[z]; z := z +1; } } x := x+1; } } method sorting(a: array<int>, low: int, high: int) requires 0 <= low && high < a.Length decreases high-low modifies a { if (low < high) { var medium: int := low + (high - low)/2; sorting(a, low, medium); sorting(a, medium+1, high); merging(a, low, medium, high); } }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Merge_Sort.dfy
215
215
Dafny program: 215
predicate quickSorted(Seq: seq<int>) { forall idx_1, idx_2 :: 0 <= idx_1 < idx_2 < |Seq| ==> Seq[idx_1] <= Seq[idx_2] } method threshold(thres:int,Seq:seq<int>) returns (Seq_1:seq<int>,Seq_2:seq<int>) ensures (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres) ensures |Seq_1| + |Seq_2| == |Seq| ensures multiset(Seq_1) + multiset(Seq_2) == multiset(Seq) { Seq_1 := []; Seq_2 := []; var i := 0; while (i < |Seq|) { if (Seq[i] <= thres) { Seq_1 := Seq_1 + [Seq[i]]; } else { Seq_2 := Seq_2 + [Seq[i]]; } i := i + 1; } } lemma Lemma_1(Seq_1:seq,Seq_2:seq) // The proof of the lemma is not necessary requires multiset(Seq_1) == multiset(Seq_2) ensures forall x | x in Seq_1 :: x in Seq_2 { forall x | x in Seq_1 ensures x in multiset(Seq_1) { var i := 0; while (i < |Seq_1|) { i := i + 1; } } } method quickSort(Seq: seq<int>) returns (Seq': seq<int>) ensures multiset(Seq) == multiset(Seq') { if |Seq| == 0 { return []; } else if |Seq| == 1 { return Seq; } else { var Seq_1,Seq_2 := threshold(Seq[0],Seq[1..]); var Seq_1' := quickSort(Seq_1); Lemma_1(Seq_1',Seq_1); var Seq_2' := quickSort(Seq_2); Lemma_1(Seq_2',Seq_2); return Seq_1' + [Seq[0]] + Seq_2'; } }
predicate quickSorted(Seq: seq<int>) { forall idx_1, idx_2 :: 0 <= idx_1 < idx_2 < |Seq| ==> Seq[idx_1] <= Seq[idx_2] } method threshold(thres:int,Seq:seq<int>) returns (Seq_1:seq<int>,Seq_2:seq<int>) ensures (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres) ensures |Seq_1| + |Seq_2| == |Seq| ensures multiset(Seq_1) + multiset(Seq_2) == multiset(Seq) { Seq_1 := []; Seq_2 := []; var i := 0; while (i < |Seq|) invariant i <= |Seq| invariant (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres) invariant |Seq_1| + |Seq_2| == i invariant multiset(Seq[..i]) == multiset(Seq_1) + multiset(Seq_2) { if (Seq[i] <= thres) { Seq_1 := Seq_1 + [Seq[i]]; } else { Seq_2 := Seq_2 + [Seq[i]]; } assert (Seq[..i] + [Seq[i]]) == Seq[..i+1]; i := i + 1; } assert (Seq[..|Seq|] == Seq); } lemma Lemma_1(Seq_1:seq,Seq_2:seq) // The proof of the lemma is not necessary requires multiset(Seq_1) == multiset(Seq_2) ensures forall x | x in Seq_1 :: x in Seq_2 { forall x | x in Seq_1 ensures x in multiset(Seq_1) { var i := 0; while (i < |Seq_1|) invariant 0 <= i <= |Seq_1| invariant forall idx_1 | 0 <= idx_1 < i :: Seq_1[idx_1] in multiset(Seq_1) { i := i + 1; } } } method quickSort(Seq: seq<int>) returns (Seq': seq<int>) ensures multiset(Seq) == multiset(Seq') decreases |Seq| { if |Seq| == 0 { return []; } else if |Seq| == 1 { return Seq; } else { var Seq_1,Seq_2 := threshold(Seq[0],Seq[1..]); var Seq_1' := quickSort(Seq_1); Lemma_1(Seq_1',Seq_1); var Seq_2' := quickSort(Seq_2); Lemma_1(Seq_2',Seq_2); assert Seq == [Seq[0]] + Seq[1..]; return Seq_1' + [Seq[0]] + Seq_2'; } }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Quick_Sort.dfy
216
216
Dafny program: 216
method selectionSorted(Array: array<int>) modifies Array ensures multiset(old(Array[..])) == multiset(Array[..]) { var idx := 0; while (idx < Array.Length) { var minIndex := idx; var idx' := idx + 1; while (idx' < Array.Length) { if (Array[idx'] < Array[minIndex]) { minIndex := idx'; } idx' := idx' + 1; } Array[idx], Array[minIndex] := Array[minIndex], Array[idx]; idx := idx + 1; } }
method selectionSorted(Array: array<int>) modifies Array ensures multiset(old(Array[..])) == multiset(Array[..]) { var idx := 0; while (idx < Array.Length) invariant 0 <= idx <= Array.Length invariant forall i,j :: 0 <= i < idx <= j < Array.Length ==> Array[i] <= Array[j] invariant forall i,j :: 0 <= i < j < idx ==> Array[i] <= Array[j] invariant multiset(old(Array[..])) == multiset(Array[..]) { var minIndex := idx; var idx' := idx + 1; while (idx' < Array.Length) invariant idx <= idx' <= Array.Length invariant idx <= minIndex < idx' <= Array.Length invariant forall k :: idx <= k < idx' ==> Array[minIndex] <= Array[k] { if (Array[idx'] < Array[minIndex]) { minIndex := idx'; } idx' := idx' + 1; } Array[idx], Array[minIndex] := Array[minIndex], Array[idx]; idx := idx + 1; } }
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Selection_Sort_Standard.dfy
218
218
Dafny program: 218
// 2. Given an array of positive and negative integers, it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5] function abs(a:int):nat { if a < 0 then -a else a } method aba(a:array<int>)returns (b:array<int>) ensures a.Length == b.Length // needed for next line ensures forall x :: 0<=x<b.Length ==> b[x] == abs(a[x]) { b := new int[a.Length]; var i:=0; while(i < a.Length) { if(a[i] < 0){ b[i] := -a[i]; } else{ b[i] := a[i]; } i := i + 1; } } method Main() { var a := new int[][1,-2,-2,1]; var b := aba(a); }
// 2. Given an array of positive and negative integers, it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5] function abs(a:int):nat { if a < 0 then -a else a } method aba(a:array<int>)returns (b:array<int>) ensures a.Length == b.Length // needed for next line ensures forall x :: 0<=x<b.Length ==> b[x] == abs(a[x]) { b := new int[a.Length]; var i:=0; while(i < a.Length) invariant 0<= i <= a.Length invariant forall x :: 0<=x<i ==> b[x] == abs(a[x]) { if(a[i] < 0){ b[i] := -a[i]; } else{ b[i] := a[i]; } i := i + 1; } } method Main() { var a := new int[][1,-2,-2,1]; var b := aba(a); assert b[..] == [1,2,2,1]; }
FlexWeek_tmp_tmpc_tfdj_3_ex2.dfy
219
219
Dafny program: 219
method Max(a:array<nat>)returns(m:int) ensures a.Length > 0 ==> forall k :: 0<=k<a.Length ==> m >= a[k]// not strong enough ensures a.Length == 0 ==> m == -1 ensures a.Length > 0 ==> m in a[..] // finally at the top // approach did not work for recusrive function { if(a.Length == 0){ return -1; } var i := 0; m := a[0]; while(i < a.Length) // invariant 0 < i <= a.Length ==> (ret_max(a,i-1) == m) { if(a[i] >= m){ m:= a[i]; } i := i+1; } } method Checker() { var a := new nat[][1,2,3,50,5,51]; // ghost var a := [1,2,3]; var n := Max(a); // assert a[..] == [1,2,3]; // assert MAXIMUM(1,2) == 2; // assert ret_max(a,a.Length-1) == 12; // assert ret_max(a,a.Length-1) == x+3; }
method Max(a:array<nat>)returns(m:int) ensures a.Length > 0 ==> forall k :: 0<=k<a.Length ==> m >= a[k]// not strong enough ensures a.Length == 0 ==> m == -1 ensures a.Length > 0 ==> m in a[..] // finally at the top // approach did not work for recusrive function { if(a.Length == 0){ return -1; } assert a.Length > 0; var i := 0; m := a[0]; assert m in a[..]; // had to show that m is in a[..], otherwise how could i assert for it while(i < a.Length) invariant 0<=i<=a.Length invariant forall k :: 0<=k<i ==> m >= a[k]// Not strong enough invariant m in a[..] // again i the array // invariant 0 < i <= a.Length ==> (ret_max(a,i-1) == m) { if(a[i] >= m){ m:= a[i]; } i := i+1; } assert m in a[..]; // } method Checker() { var a := new nat[][1,2,3,50,5,51]; // ghost var a := [1,2,3]; var n := Max(a); // assert a[..] == [1,2,3]; assert n == 51; // assert MAXIMUM(1,2) == 2; // assert ret_max(a,a.Length-1) == 12; // assert ret_max(a,a.Length-1) == x+3; }
FlexWeek_tmp_tmpc_tfdj_3_ex3.dfy
220
220
Dafny program: 220
method join(a:array<int>,b:array<int>) returns (c:array<int>) ensures a[..] + b[..] == c[..] ensures multiset(a[..] + b[..]) == multiset(c[..]) ensures multiset(a[..]) + multiset(b[..]) == multiset(c[..]) ensures a.Length+b.Length == c.Length // Forall ensures forall i :: 0<=i<a.Length ==> c[i] == a[i] ensures forall i_2,j_2:: a.Length <= i_2 < c.Length && 0<=j_2< b.Length && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] { c := new int[a.Length+b.Length]; var i:= 0; while(i < a.Length) { c[i] := a[i]; i := i +1; } i:= a.Length; var j := 0; while(i < c.Length && j<b.Length) // missed j condition //Sequences //Multiset // Forall a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] // curr loop 0<=k_2<a.Length && a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] && c[k_2] == a[k_2] // prev loop+curr loop { c[i] := b[j]; i := i +1; j := j +1; } // assert j == b.Length; // assert b[..]==b[..b.Length]; // assert j + a.Length == c.Length; // assert multiset(c[..a.Length]) == multiset(a[..a.Length]); // assert multiset(b[..]) == multiset(b[..j]); // assert multiset(c[a.Length..j+a.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(b[..]); // assert multiset(c[0..c.Length]) == multiset(c[0..a.Length]) + multiset(c[a.Length..c.Length]); // uncomment } method Check(){ var a := new int[][1,2,3]; var b := new int[][4,5]; var c := new int[][1,2,3,4,5]; var d:= join(a,b); // print n[..]; }
method join(a:array<int>,b:array<int>) returns (c:array<int>) ensures a[..] + b[..] == c[..] ensures multiset(a[..] + b[..]) == multiset(c[..]) ensures multiset(a[..]) + multiset(b[..]) == multiset(c[..]) ensures a.Length+b.Length == c.Length // Forall ensures forall i :: 0<=i<a.Length ==> c[i] == a[i] ensures forall i_2,j_2:: a.Length <= i_2 < c.Length && 0<=j_2< b.Length && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] { c := new int[a.Length+b.Length]; var i:= 0; while(i < a.Length) invariant 0 <= i <=a.Length invariant c[..i] == a[..i] invariant multiset(c[..i]) == multiset(a[..i]) invariant forall k :: 0<=k<i<a.Length ==> c[k] == a[k] { c[i] := a[i]; i := i +1; } i:= a.Length; var j := 0; while(i < c.Length && j<b.Length) // missed j condition invariant 0<=j<=b.Length invariant 0 <= a.Length <= i <= c.Length invariant c[..a.Length] == a[..a.Length] //Sequences invariant c[a.Length..i] == b[..j] // prev loop invariant c[..a.Length] + c[a.Length..i] == a[..a.Length] + b[..j] // prev loop + prev curr loop //Multiset invariant multiset(c[a.Length..i]) == multiset(b[..j]) // prev loop invariant multiset( c[..a.Length] + c[a.Length..i]) == multiset(a[..a.Length] + b[..j]) // prev loop + prev curr loop // Forall invariant forall k :: 0<=k<a.Length ==> c[k] == a[k] // prev loop invariant forall i_2,j_2:: a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] // curr loop invariant forall k_2,i_2,j_2:: 0<=k_2<a.Length && a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] && c[k_2] == a[k_2] // prev loop+curr loop { c[i] := b[j]; i := i +1; j := j +1; } // assert j == b.Length; // assert b[..]==b[..b.Length]; // assert j + a.Length == c.Length; // assert multiset(c[..a.Length]) == multiset(a[..a.Length]); // assert multiset(b[..]) == multiset(b[..j]); // assert multiset(c[a.Length..j+a.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(b[..]); // assert multiset(c[0..c.Length]) == multiset(c[0..a.Length]) + multiset(c[a.Length..c.Length]); // uncomment assert a[..] + b[..] == c[..]; assert multiset(a[..]) + multiset(b[..]) == multiset(c[..]); } method Check(){ var a := new int[][1,2,3]; var b := new int[][4,5]; var c := new int[][1,2,3,4,5]; var d:= join(a,b); assert d[..] == a[..] + b[..]; // works assert multiset(d[..]) == multiset(a[..] + b[..]); assert multiset(d[..]) == multiset(a[..]) + multiset(b[..]); assert d[..] == c[..]; // works assert d[..] == c[..]; //doesn't // print n[..]; }
FlexWeek_tmp_tmpc_tfdj_3_ex4.dfy
221
221
Dafny program: 221
// Write an *iterative* Dafny method Reverse with signature: // method Reverse(a: array<char>) returns (b: array<char>) // which takes an input array of characters 'a' and outputs array 'b' consisting of // the elements of the input array in reverse order. The following conditions apply: // - the input array cannot be empty // - the input array is not modified // - you must use iteration // - not permitted is an *executable* (parallel) forall statement // - not permitted are any other predicates, functions or methods // For the purposes of this practice exercise, I'll include a test method. method Reverse(a: array<char>) returns (b: array<char>) requires a.Length > 0 ensures a.Length == b.Length ensures forall k :: 0 <= k < a.Length ==> b[k] == a[(a.Length-1) - k]; { b := new char[a.Length]; var i:= 0; while(i < a.Length) // invariant 0 < i <= a.Length-1 ==> b[i-1] == a[(a.Length-1) - i+1] // Not good enough { b[i] := a[(a.Length-1) - i]; i := i + 1; } // assert forall k :: 0 <= k < a.Length ==> a[k] == b[(a.Length-1) - k]; } method Main() { var a := new char[8]; a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r'; var b := Reverse(a); print b[..]; a := new char[1]; a[0] := '!'; b := Reverse(a); print b[..], '\n'; } // Notice it compiles and the executable generates output (just to see the arrays printed in reverse).
// Write an *iterative* Dafny method Reverse with signature: // method Reverse(a: array<char>) returns (b: array<char>) // which takes an input array of characters 'a' and outputs array 'b' consisting of // the elements of the input array in reverse order. The following conditions apply: // - the input array cannot be empty // - the input array is not modified // - you must use iteration // - not permitted is an *executable* (parallel) forall statement // - not permitted are any other predicates, functions or methods // For the purposes of this practice exercise, I'll include a test method. method Reverse(a: array<char>) returns (b: array<char>) requires a.Length > 0 ensures a.Length == b.Length ensures forall k :: 0 <= k < a.Length ==> b[k] == a[(a.Length-1) - k]; { b := new char[a.Length]; assert b.Length == a.Length; var i:= 0; while(i < a.Length) invariant 0<=i<=a.Length // invariant 0 < i <= a.Length-1 ==> b[i-1] == a[(a.Length-1) - i+1] // Not good enough invariant forall k :: 0 <= k < i ==> b[k] == a[(a.Length-1) - k] { b[i] := a[(a.Length-1) - i]; i := i + 1; } // assert forall k :: 0 <= k < a.Length ==> a[k] == b[(a.Length-1) - k]; } method Main() { var a := new char[8]; a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r'; var b := Reverse(a); assert b[..] == [ 'r', 'e', 'v', 'e', 'r', 's', 'e', 'd' ]; print b[..]; a := new char[1]; a[0] := '!'; b := Reverse(a); assert b[..] == [ '!' ]; print b[..], '\n'; } // Notice it compiles and the executable generates output (just to see the arrays printed in reverse).
FlexWeek_tmp_tmpc_tfdj_3_reverse.dfy
223
223
Dafny program: 223
method Fact(x: int) returns (y: int) requires x >= 0; { y := 1; var z := 0; while(z != x) { z := z + 1; y := y * z; } } method Main() { var a := Fact(87); print a; }
method Fact(x: int) returns (y: int) requires x >= 0; { y := 1; var z := 0; while(z != x) decreases x - z; invariant 0 <= x-z; { z := z + 1; y := y * z; } } method Main() { var a := Fact(87); print a; }
Formal-Methods-Project_tmp_tmphh2ar2xv_Factorial.dfy
224
224
Dafny program: 224
predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |str| < |pre| { return false; } else if pre[..] == str[..|pre|] { return true; } else{ return false; } } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { // Initializing variables var i := 0; res := false; // Check if sub is a prefix of str[i..] and if not, keep incrementing until i = |str| while i <= |str| // Invariant to stay within bounds // Invariant to show that for all j that came before i, no prefix has been found // Telling dafny that i is that value that is increasing //invariant res <==> isSubstringPred(sub, str) { // Check if the substring is a prefix var temp := isPrefix(sub, str[i..]); // If so, return true as the prefix is a substring of the string if temp == true { return true; } // Otherwise, increment i and try again i := i + 1; } // If we have reached this point, it means that no substring has been found, hence return false return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { // Check that both strings are larger than k if (k > |str1| || k > |str2| ){ return false; } // Initialize variables var i := 0; var temp := false; // Don't want to exceed the bounds of str1 when checking for the element that is k entries away while i <= |str1|-k // Invariant to stay within bounds // Invariant to show that when temp is true, it is a substring // Invariant to show that when temp is false, it is not a substring // Telling dafny that i is that value that is increasing { // Get an index from the array position were are at to the array position that is k away and check the substring temp := isSubstring(str1[i..(i + k)], str2); if temp == true { return true; } i := i + 1; } return false; } lemma haveCommon0SubstringLemma(str1:string, str2:string) ensures haveCommonKSubstringPred(0,str1,str2) { } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var temp := false; var i := |str1|+1; len := i; // Idea is to start the counter at |str1| and decrement until common string is found while i > 0 // Invariant to stay within bounds // When temp is true, there is a common sub string of size i // When temp is false, there is not a common sub string of size i // When temp is false, there is no common sub string of sizes >= i // When temp is true, there is no common sub string of sizes > i { i:= i-1; len := i; temp := haveCommonKSubstring(i, str1, str2); if temp == true { break; } } haveCommon0SubstringLemma(str1, str2); return len; }
predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |str| < |pre| { return false; } else if pre[..] == str[..|pre|] { return true; } else{ return false; } } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { // Initializing variables var i := 0; res := false; // Check if sub is a prefix of str[i..] and if not, keep incrementing until i = |str| while i <= |str| // Invariant to stay within bounds invariant 0 <= i <= |str| + 1 // Invariant to show that for all j that came before i, no prefix has been found invariant forall j :: (0 <= j < i ==> isNotPrefixPred(sub, str[j..])) // Telling dafny that i is that value that is increasing decreases |str| - i //invariant res <==> isSubstringPred(sub, str) { // Check if the substring is a prefix var temp := isPrefix(sub, str[i..]); // If so, return true as the prefix is a substring of the string if temp == true { return true; } // Otherwise, increment i and try again i := i + 1; } // If we have reached this point, it means that no substring has been found, hence return false return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { // Check that both strings are larger than k if (k > |str1| || k > |str2| ){ return false; } // Initialize variables var i := 0; var temp := false; // Don't want to exceed the bounds of str1 when checking for the element that is k entries away while i <= |str1|-k // Invariant to stay within bounds invariant 0 <= i <= (|str1|-k) + 1 // Invariant to show that when temp is true, it is a substring invariant temp ==> 0 <= i <= (|str1| - k) && isSubstringPred(str1[i..i+k], str2) // Invariant to show that when temp is false, it is not a substring invariant !temp ==> (forall m,n :: (0 <= m < i && n == m+k) ==> isNotSubstringPred(str1[m..n], str2)) // Telling dafny that i is that value that is increasing decreases |str1| - k - i { // Get an index from the array position were are at to the array position that is k away and check the substring temp := isSubstring(str1[i..(i + k)], str2); if temp == true { return true; } i := i + 1; } return false; } lemma haveCommon0SubstringLemma(str1:string, str2:string) ensures haveCommonKSubstringPred(0,str1,str2) { assert isPrefixPred(str1[0..0], str2[0..]); } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var temp := false; var i := |str1|+1; len := i; // Idea is to start the counter at |str1| and decrement until common string is found while i > 0 decreases i // Invariant to stay within bounds invariant 0 <= i <= |str1| + 1 // When temp is true, there is a common sub string of size i invariant temp ==> haveCommonKSubstringPred(i, str1, str2) // When temp is false, there is not a common sub string of size i invariant !temp ==> haveNotCommonKSubstringPred(i, str1, str2) // When temp is false, there is no common sub string of sizes >= i invariant !temp ==> (forall k :: i <= k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) // When temp is true, there is no common sub string of sizes > i invariant temp ==> (forall k :: (i < k <= |str1|) ==> !haveCommonKSubstringPred(k,str1,str2)) { i:= i-1; len := i; temp := haveCommonKSubstring(i, str1, str2); if temp == true { break; } } haveCommon0SubstringLemma(str1, str2); return len; }
Formal-Verification-Project_tmp_tmp9gmwsmyp_strings3.dfy
225
225
Dafny program: 225
predicate isPrefixPredicate(pre: string, str:string) { |str| >= |pre| && pre <= str } method isPrefix(pre: string, str: string) returns (res: bool) ensures |pre| > |str| ==> !res ensures res == isPrefixPredicate(pre, str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPredicate (sub: string, str:string) { |str| >= |sub| && (exists i :: 0 <= i <= |str| && isPrefixPredicate(sub, str[i..])) } method isSubstring(sub: string, str: string) returns (res:bool) ensures res == isSubstringPredicate(sub, str) { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPredicate(k: nat, str1: string, str2: string) { |str1| >= k && |str2| >= k && (exists i :: 0 <= i <= |str1| - k && isSubstringPredicate((str1[i..])[..k], str2)) } method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures |str1| < k || |str2| < k ==> !found ensures haveCommonKSubstringPredicate(k,str1,str2) == found { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 { var isSub := isSubstring(str1[i..][..k], str2); if isSub { return true; } i := i-1; } return false; } predicate maxCommonSubstringPredicate(str1: string, str2: string, len:nat) { forall k :: len < k <= |str1| ==> !haveCommonKSubstringPredicate(k, str1, str2) } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) ensures len <= |str1| && len <= |str2| ensures len >= 0 ensures maxCommonSubstringPredicate(str1, str2, len) { var i := |str1|; while i > 0 { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } return 0; }
predicate isPrefixPredicate(pre: string, str:string) { |str| >= |pre| && pre <= str } method isPrefix(pre: string, str: string) returns (res: bool) ensures |pre| > |str| ==> !res ensures res == isPrefixPredicate(pre, str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| decreases |pre| - i invariant 0 <= i <= |pre| invariant forall j :: 0 <= j < i ==> pre[j] == str[j] { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPredicate (sub: string, str:string) { |str| >= |sub| && (exists i :: 0 <= i <= |str| && isPrefixPredicate(sub, str[i..])) } method isSubstring(sub: string, str: string) returns (res:bool) ensures res == isSubstringPredicate(sub, str) { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 decreases i invariant i >= -1 invariant forall j :: i < j <= |str|-|sub| ==> !(isPrefixPredicate(sub, str[j..])) { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPredicate(k: nat, str1: string, str2: string) { |str1| >= k && |str2| >= k && (exists i :: 0 <= i <= |str1| - k && isSubstringPredicate((str1[i..])[..k], str2)) } method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures |str1| < k || |str2| < k ==> !found ensures haveCommonKSubstringPredicate(k,str1,str2) == found { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 decreases i invariant i >= -1 invariant forall j :: i < j <= |str1| - k ==> !isSubstringPredicate(str1[j..][..k], str2) { var isSub := isSubstring(str1[i..][..k], str2); if isSub { return true; } i := i-1; } return false; } predicate maxCommonSubstringPredicate(str1: string, str2: string, len:nat) { forall k :: len < k <= |str1| ==> !haveCommonKSubstringPredicate(k, str1, str2) } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) ensures len <= |str1| && len <= |str2| ensures len >= 0 ensures maxCommonSubstringPredicate(str1, str2, len) { var i := |str1|; while i > 0 decreases i invariant i >= 0 invariant forall j :: i < j <= |str1| ==> !haveCommonKSubstringPredicate(j, str1, str2) { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } assert i == 0; return 0; }
Formal-Verification_tmp_tmpuyt21wjt_Dafny_strings1.dfy
226
226
Dafny program: 226
// We spent 2h each on this assignment predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 { var t := i+k; var isSub := isSubstring(str1[i..t], str2); if isSub { return true; } i := i-1; } return false; } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var i := |str1|; while i > 0 { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } return 0; }
// We spent 2h each on this assignment predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| decreases |pre| - i invariant 0 <= i <= |pre| invariant forall j :: 0 <= j < i ==> pre[j] == str[j] { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 decreases i invariant i >= -1 invariant forall j :: i < j <= |str|-|sub| ==> !(isPrefixPred(sub, str[j..])) { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 decreases i invariant i >= -1 invariant forall j,t :: i < j <= |str1| - k && t==j+k ==> !isSubstringPred(str1[j..t], str2) { var t := i+k; var isSub := isSubstring(str1[i..t], str2); if isSub { return true; } i := i-1; } return false; } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var i := |str1|; while i > 0 decreases i invariant i >= 0 invariant forall j :: i < j <= |str1| ==> !haveCommonKSubstringPred(j, str1, str2) { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } assert i == 0; assert isPrefixPred(str1[0..0],str2[0..]); return 0; }
Formal-Verification_tmp_tmpuyt21wjt_Dafny_strings3.dfy
227
227
Dafny program: 227
method multipleReturns (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures less < x < more method multipleReturns2 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more + less == 2*x // TODO: Hacer en casa method multipleReturns3 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more - less == 2*y function factorial(n:int):int requires n>=0 { if n==0 || n==1 then 1 else n*factorial(n-1) } // PROGRAMA VERIFICADOR DE WHILE method ComputeFact (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { f:=1; var x:=n; while x > 0 { f:= f*x; x:=x-1; } } method ComputeFact2 (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { var x:= 0; f:= 1; while x<n { x:=x+1; f:= f*x; } } // n>=1 ==> 1 + 3 + 5 + ... + (2*n-1) = n*n method Sqare(a:int) returns (x:int) requires a>=1 ensures x == a*a { var y:=1; x:=1; while y < a { y:= y+1; x:= x+ (2*y-1); } } function sumSerie(n:int):int requires n >=1 { if n==1 then 1 else sumSerie(n-1) + 2*n -1 } lemma {:induction false} Sqare_Lemma (n:int) requires n>=1 ensures sumSerie(n) == n*n { if n==1 {} else{ Sqare_Lemma(n-1); calc == { sumSerie(n); sumSerie(n-1) + 2*n -1; { Sqare_Lemma(n-1); } (n-1)*(n-1) + 2*n -1; n*n-2*n+1 +2*n -1; n*n; } } } method Sqare2(a:int) returns (x:int) requires a>=1 ensures x == a*a { var y:=1; x:=1; while y < a { y:= y+1; x:= x +2*y -1; } }
method multipleReturns (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures less < x < more method multipleReturns2 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more + less == 2*x // TODO: Hacer en casa method multipleReturns3 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more - less == 2*y function factorial(n:int):int requires n>=0 { if n==0 || n==1 then 1 else n*factorial(n-1) } // PROGRAMA VERIFICADOR DE WHILE method ComputeFact (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { assert 0 <= n <= n && 1*factorial(n) == factorial(n); f:=1; assert 0 <= n <= n && f*factorial(n) == factorial(n); var x:=n; assert 0 <= x <= n && f*factorial(x) == factorial(n); while x > 0 invariant 0 <= x <= n; invariant f*factorial(x)== factorial(n); decreases x-0; { assert 0 <= x-1 <= n && (f*x)*factorial(x-1) == factorial(n); f:= f*x; assert 0 <= x-1 <= n && f*factorial(x-1) == factorial(n); x:=x-1; assert 0 <= x <= n && f*factorial(x) == factorial(n); } assert 0 <= x <= n && f*factorial(x) == factorial(n); } method ComputeFact2 (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { var x:= 0; f:= 1; while x<n invariant 0<=x<=n; invariant f==factorial(x); decreases n - x; { x:=x+1; f:= f*x; assert 0<=x<=n && f==factorial(x); } } // n>=1 ==> 1 + 3 + 5 + ... + (2*n-1) = n*n method Sqare(a:int) returns (x:int) requires a>=1 ensures x == a*a { assert 1==1 && 1 <= 1 <= a; var y:=1; assert y*y==1 && 1 <= y <= a; x:=1; while y < a invariant 1 <= y <= a; invariant y*y==x; { assert (y+1)*(y+1)==x+ (2*(y+1)-1) && 1 <= (y+1) <= a; y:= y+1; assert y*y==x+ (2*y-1) && 1 <= y <= a; x:= x+ (2*y-1); assert y*y==x && 1 <= y <= a; } assert y*y==x && 1 <= y <= a; } function sumSerie(n:int):int requires n >=1 { if n==1 then 1 else sumSerie(n-1) + 2*n -1 } lemma {:induction false} Sqare_Lemma (n:int) requires n>=1 ensures sumSerie(n) == n*n { if n==1 {} else{ Sqare_Lemma(n-1); assert sumSerie(n-1) ==(n-1)*(n-1); calc == { sumSerie(n); sumSerie(n-1) + 2*n -1; { Sqare_Lemma(n-1); assert sumSerie(n-1) ==(n-1)*(n-1); } (n-1)*(n-1) + 2*n -1; n*n-2*n+1 +2*n -1; n*n; } assert sumSerie(n) == n*n; } } method Sqare2(a:int) returns (x:int) requires a>=1 ensures x == a*a { assert 1 <= 1 <= a && 1==1*1; var y:=1; assert 1 <= y <= a && 1==y*y; x:=1; assert 1 <= y <= a && x==y*y; while y < a invariant 1 <= y <= a invariant x==y*y decreases a - y { assert 1 <= (y+1) <= a && (x+2*(y+1)-1)==(y+1)*(y+1); y:= y+1; assert 1 <= y <= a && (x+2*y-1)==y*y; x:= x +2*y -1; assert 1 <= y <= a && x==y*y; } assert 1 <= y <= a && x==y*y; }
Formal-methods-of-software-development_tmp_tmppryvbyty_Bloque 1_Lab3.dfy
228
228
Dafny program: 228
/*predicate palindrome<T(==)> (s:seq<T>) { forall i:: 0<=i<|s| ==> s[i] == s[|s|-i-1] } */ // SUM OF A SEQUENCE OF INTEGERS function sum(v: seq<int>): int { if v==[] then 0 else if |v|==1 then v[0] else v[0]+sum(v[1..]) } /* method vector_Sum(v:seq<int>) returns (x:int) ensures x == sum(v) { var n := 0 ; x := 0; while n != |v| { left_sum_Lemma(v, n+1); x, n := x + v[n], n + 1; } } // Structural Induction on Sequences lemma left_sum_Lemma(r:seq<int>, k:int) requires 0 <= k < |r| ensures sum(r[..k]) + r[k] == sum(r[..k+1]); { if |r|==1 || k==0{ } else { left_sum_Lemma(r[1..], k); calc { sum(r[..k+1]); sum(r[..k]) + [r[k]]; } } } // MAXIMUM OF A SEQUENCE method maxSeq(v: seq<int>) returns (max:int) requires |v| >= 1 ensures forall i :: 0 <= i < |v| ==> max >= v[i] ensures max in v { max := v[0]; var v' := v[1..]; ghost var t := [v[0]]; while |v'| >= 1 { if v'[0] > max { max := v'[0]; } v', t := v'[1..], t + [v'[0]]; } } // TODO: Hacer // Derivar formalmente un calculo incremental de j*j*j method Cubes (n:int) returns (s:seq<int>) requires n >= 0 ensures |s| == n ensures forall i:int :: 0 <= i < n ==> s[i] == i*i*i { s := []; var c, j, k, m := 0,0,1,6; while j < n { s := s+[c]; //c := (j+1)*(j+1)*(j+1); c := c + k; k := k + 6*j + 6; m := m + 6; //assert m == 6*(j+1) + 6 == 6*j + 6 + 6; == 3*j*j + 9*j + 7 == 3*j*j + 3*j + 1 + (6*j + 6); //assert c == (j+1)*(j+1)*(j+1) == j*j*j + 3*j*j + 3*j + 1; j := j+1; //assert m == 6*j + 6; //assert k == 3*j*j + 3*j + 1; //assert c == j*j*j; } } // REVERSE OF A SEQUENCE function reverse<T> (s:seq<T>):seq<T> { if s==[] then [] else reverse(s[1..])+[s[0]] } function seq2set<T> (s:seq<T>): set<T> { if s==[] then {} else {s[0]}+seq2set(s[1..]) } lemma seq2setRev_Lemma<T> (s:seq<T>) ensures seq2set(reverse(s)) == seq2set(s) { if s==[]{} else { seq2setRev_Lemma(s[1..]); calc { seq2set(s); seq2set([s[0]]+s[1..]); { concat_seq2set_Lemma([s[0]], s[1..]); } seq2set([s[0]]) + seq2set(s[1..]); { seq2setRev_Lemma(s[1..]); } seq2set([s[0]]) + seq2set(reverse(s[1..])); seq2set(reverse(s[1..])) + seq2set([s[0]]); { concat_seq2set_Lemma(reverse(s[1..]), [s[0]]); } seq2set(reverse(s[1..]) + [s[0]]); { } seq2set(reverse(s)); } } } lemma concat_seq2set_Lemma<T>(s1:seq<T>,s2:seq<T>) ensures seq2set(s1+s2) == seq2set(s1) + seq2set(s2) { if s1==[]{ } else { concat_seq2set_Lemma(s1[1..], s2); calc{ seq2set(s1) + seq2set(s2); seq2set([s1[0]]+s1[1..]) + seq2set(s2); seq2set([s1[0]]) + seq2set(s1[1..]) + seq2set(s2); { concat_seq2set_Lemma(s1[1..], s2); } seq2set([s1[0]]) + seq2set(s1[1..]+s2); { } seq2set([s1[0]]) + seq2set((s1+s2)[1..]); { // assert seq2set([s1[0]]) + seq2set((s1+s2)[1..]) == seq2set(s1+s2); var ls:= s1+s2; calc { seq2set([s1[0]]) + seq2set((s1+s2)[1..]); seq2set([ls[0]])+ seq2set(ls[1..]); seq2set([ls[0]]+ ls[1..]); seq2set(ls); seq2set(s1+s2); } } seq2set(s1+s2); } } } // REVERSE IS ITS OWN INVERSE lemma Rev_Lemma<T(==)>(s:seq<T>) //ensures forall i :: 0 <= i < |s| ==> s[i] == reverse(s)[|s|-1-i] lemma ItsOwnInverse_Lemma<T> (s:seq<T>) ensures s == reverse(reverse(s)) { if s==[]{} else{ ItsOwnInverse_Lemma(s[1..]); calc { reverse(reverse(s)); reverse(reverse(s[1..])+[s[0]]); reverse(reverse([s[0]]+s[1..])); { } reverse(reverse(s[1..]) + [s[0]]); { // TODO: Demostrar este assume assume reverse(reverse(s[1..]) + [s[0]]) == [s[0]] + reverse(reverse(s[1..])); } [s[0]] + reverse(reverse(s[1..])); { ItsOwnInverse_Lemma(s[1..]); } [s[0]]+s[1..]; s; } } } // SCALAR PRODUCT OF TWO VECTORS OF INTEGER function scalar_product (v1:seq<int>, v2:seq<int>):int requires |v1| == |v2| { if v1 == [] then 0 else v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]) } lemma scalar_product_Lemma (v1:seq<int>, v2:seq<int>) requires |v1| == |v2| > 0 ensures scalar_product(v1,v2) == scalar_product(v1[..|v1|-1],v2[..|v2|-1]) + v1[|v1|-1] * v2[|v2|-1] { // INDUCCION EN LA LONGITUD DE V1 if |v1| == 0 && |v2| == 0 {} else if |v1| == 1 {} else { // Se crean estas variables para simplificar las operaciones var v1r:= v1[1..]; var v2r:= v2[1..]; var t1:= |v1[1..]|-1; var t2:= |v2[1..]|-1; // Se realiza la induccion utilizando las variables scalar_product_Lemma(v1r, v2r); scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI // Se demuestra que la propiedad se mantiene calc{ scalar_product(v1,v2); v1[0]*v2[0] + scalar_product(v1r, v2r); v1[0]*v2[0] + scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; { scalar_product_Lemma(v1r, v2r); scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI } v1[0]*v2[0] + scalar_product(v1r,v2r); v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]); scalar_product(v1,v2); } } } // MULTISETS method multiplicity_examples<T> () { var m := multiset{2,4,6,2,1,3,1,7,1,5,4,7,8,1,6}; } // REVERSE HAS THE SAME MULTISET lemma seqMultiset_Lemma<T> (s:seq<T>) ensures multiset(reverse(s)) == multiset(s) { if s==[]{} else { seqMultiset_Lemma(s[1..]); calc { multiset(reverse(s)); multiset(reverse(s[1..]) + [s[0]]); multiset(reverse(s[1..])) + multiset{[s[0]]}; multiset(s[1..]) + multiset{[s[0]]}; multiset(s); } } } */ lemma empty_Lemma<T> (r:seq<T>) requires multiset(r) == multiset{} ensures r == [] { if r != [] { } } lemma elem_Lemma<T> (s:seq<T>,r:seq<T>) requires s != [] && multiset(s) == multiset(r) ensures exists i :: 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); // SEQUENCES WITH EQUAL MULTISETS HAVE EQUAL SUMS lemma sumElems_Lemma(s:seq<int>, r:seq<int>) requires multiset(s) == multiset(r) ensures sum(s) == sum(r) { if s==[]{ empty_Lemma(r); } else { // Con este lema demuestro que el elemento que le quito a s tambien se lo quito a r y de esta manera // poder hacer la induccion elem_Lemma(s,r); var i :| 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); sumElems_Lemma(s[1..], r[..i]+r[i+1..]); // Hago la llamada recursiva sumElems_Lemma(s[1..], r[..i]+r[i+1..]); calc { sum(s); s[0]+sum(s[1..]); { sumElems_Lemma(s[1..], r[..i]+r[i+1..]); } s[0]+sum(r[..i]+r[i+1..]); { } r[i]+sum(r[..i]+r[i+1..]); { // TODO: No consigo acertarlo assume r[i]+sum(r[..i]+r[i+1..]) == sum([r[i]]+r[..i] + r[i+1..]) == sum(r); } sum(r); } } }
/*predicate palindrome<T(==)> (s:seq<T>) { forall i:: 0<=i<|s| ==> s[i] == s[|s|-i-1] } */ // SUM OF A SEQUENCE OF INTEGERS function sum(v: seq<int>): int decreases v { if v==[] then 0 else if |v|==1 then v[0] else v[0]+sum(v[1..]) } /* method vector_Sum(v:seq<int>) returns (x:int) ensures x == sum(v) { var n := 0 ; x := 0; while n != |v| invariant 0 <= n <= |v| invariant x==sum(v[..n]) { assert x == sum(v[..n]) && 0 <= n+1 <= |v|; assert x + v[n] == sum(v[..n])+ v[n] && 0 <= n+1 <= |v|; left_sum_Lemma(v, n+1); assert x + v[n] == sum(v[..n+1]) && 0 <= n+1 <= |v|; x, n := x + v[n], n + 1; assert x==sum(v[..n]) && 0 <= n <= |v|; } assert v== v[..v]; assert sum(v)==sum(v[..n]); assert x == sum(v) && 0 <= n <= |v|; assert x==sum(v[..n]) && 0 <= n <= |v|; } // Structural Induction on Sequences lemma left_sum_Lemma(r:seq<int>, k:int) requires 0 <= k < |r| ensures sum(r[..k]) + r[k] == sum(r[..k+1]); { if |r|==1 || k==0{ assert sum(r[..0])+r[0]== sum(r[..1]); } else { left_sum_Lemma(r[1..], k); assert sum(r[1..][..k]) + r[k] == sum(r[1..][..k+1]); calc { sum(r[..k+1]); sum(r[..k]) + [r[k]]; } } } // MAXIMUM OF A SEQUENCE method maxSeq(v: seq<int>) returns (max:int) requires |v| >= 1 ensures forall i :: 0 <= i < |v| ==> max >= v[i] ensures max in v { max := v[0]; var v' := v[1..]; ghost var t := [v[0]]; while |v'| >= 1 invariant forall i :: 0 <= i < |t| ==> max >= t[i] invariant v == t + v' invariant max in t decreases |v'| - 1 { if v'[0] > max { max := v'[0]; } v', t := v'[1..], t + [v'[0]]; } } // TODO: Hacer // Derivar formalmente un calculo incremental de j*j*j method Cubes (n:int) returns (s:seq<int>) requires n >= 0 ensures |s| == n ensures forall i:int :: 0 <= i < n ==> s[i] == i*i*i { s := []; var c, j, k, m := 0,0,1,6; while j < n invariant 0 <= j ==|s| <= n invariant forall i:int :: 0 <= i < j ==> s[i] == i*i*i invariant c == j*j*j invariant k == 3*j*j + 3*j + 1 invariant m == 6*j + 6 { s := s+[c]; //c := (j+1)*(j+1)*(j+1); c := c + k; k := k + 6*j + 6; m := m + 6; //assert m == 6*(j+1) + 6 == 6*j + 6 + 6; assert k == 3*(j+1)*(j+1) + 3*(j+1) + 1 == 3*j*j + 9*j + 7 == 3*j*j + 3*j + 1 + (6*j + 6); //assert c == (j+1)*(j+1)*(j+1) == j*j*j + 3*j*j + 3*j + 1; j := j+1; //assert m == 6*j + 6; //assert k == 3*j*j + 3*j + 1; //assert c == j*j*j; } } // REVERSE OF A SEQUENCE function reverse<T> (s:seq<T>):seq<T> { if s==[] then [] else reverse(s[1..])+[s[0]] } function seq2set<T> (s:seq<T>): set<T> { if s==[] then {} else {s[0]}+seq2set(s[1..]) } lemma seq2setRev_Lemma<T> (s:seq<T>) ensures seq2set(reverse(s)) == seq2set(s) { if s==[]{} else { seq2setRev_Lemma(s[1..]); assert seq2set(reverse(s[1..])) == seq2set(s[1..]); calc { seq2set(s); seq2set([s[0]]+s[1..]); { concat_seq2set_Lemma([s[0]], s[1..]); assert seq2set([s[0]]+s[1..]) == seq2set([s[0]]) + seq2set(s[1..]); } seq2set([s[0]]) + seq2set(s[1..]); { seq2setRev_Lemma(s[1..]); assert seq2set(reverse(s[1..])) == seq2set(s[1..]); } seq2set([s[0]]) + seq2set(reverse(s[1..])); seq2set(reverse(s[1..])) + seq2set([s[0]]); { concat_seq2set_Lemma(reverse(s[1..]), [s[0]]); } seq2set(reverse(s[1..]) + [s[0]]); { assert reverse([s[0]]+s[1..]) == reverse(s); assert [s[0]]+s[1..] == s; assert reverse(s[1..])+[s[0]] == reverse(s); } seq2set(reverse(s)); } } } lemma concat_seq2set_Lemma<T>(s1:seq<T>,s2:seq<T>) ensures seq2set(s1+s2) == seq2set(s1) + seq2set(s2) { if s1==[]{ assert seq2set(s2) == seq2set([]) + seq2set(s2); assert []==s1; assert []+s2==s2; assert s1+s2==s2; assert seq2set(s1+s2)==seq2set(s2); } else { concat_seq2set_Lemma(s1[1..], s2); assert seq2set(s1[1..]+s2) == seq2set(s1[1..]) + seq2set(s2); calc{ seq2set(s1) + seq2set(s2); seq2set([s1[0]]+s1[1..]) + seq2set(s2); seq2set([s1[0]]) + seq2set(s1[1..]) + seq2set(s2); { concat_seq2set_Lemma(s1[1..], s2); assert seq2set(s1[1..]+s2) == seq2set(s1[1..]) + seq2set(s2); } seq2set([s1[0]]) + seq2set(s1[1..]+s2); { assert s1[1..]+s2 == (s1+s2)[1..]; } seq2set([s1[0]]) + seq2set((s1+s2)[1..]); { // assert seq2set([s1[0]]) + seq2set((s1+s2)[1..]) == seq2set(s1+s2); var ls:= s1+s2; calc { seq2set([s1[0]]) + seq2set((s1+s2)[1..]); seq2set([ls[0]])+ seq2set(ls[1..]); seq2set([ls[0]]+ ls[1..]); seq2set(ls); seq2set(s1+s2); } } seq2set(s1+s2); } } } // REVERSE IS ITS OWN INVERSE lemma Rev_Lemma<T(==)>(s:seq<T>) //ensures forall i :: 0 <= i < |s| ==> s[i] == reverse(s)[|s|-1-i] lemma ItsOwnInverse_Lemma<T> (s:seq<T>) ensures s == reverse(reverse(s)) { if s==[]{} else{ ItsOwnInverse_Lemma(s[1..]); assert s[1..] == reverse(reverse(s[1..])); calc { reverse(reverse(s)); reverse(reverse(s[1..])+[s[0]]); reverse(reverse([s[0]]+s[1..])); { assert reverse([s[0]]+ s[1..]) == reverse(s[1..]) + [s[0]]; assert reverse(reverse([s[0]]+ s[1..])) == reverse(reverse(s[1..]) + [s[0]]); } reverse(reverse(s[1..]) + [s[0]]); { // TODO: Demostrar este assume assume reverse(reverse(s[1..]) + [s[0]]) == [s[0]] + reverse(reverse(s[1..])); } [s[0]] + reverse(reverse(s[1..])); { ItsOwnInverse_Lemma(s[1..]); assert s[1..] == reverse(reverse(s[1..])); } [s[0]]+s[1..]; s; } } } // SCALAR PRODUCT OF TWO VECTORS OF INTEGER function scalar_product (v1:seq<int>, v2:seq<int>):int requires |v1| == |v2| { if v1 == [] then 0 else v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]) } lemma scalar_product_Lemma (v1:seq<int>, v2:seq<int>) requires |v1| == |v2| > 0 ensures scalar_product(v1,v2) == scalar_product(v1[..|v1|-1],v2[..|v2|-1]) + v1[|v1|-1] * v2[|v2|-1] { // INDUCCION EN LA LONGITUD DE V1 if |v1| == 0 && |v2| == 0 {} else if |v1| == 1 {} else { // Se crean estas variables para simplificar las operaciones var v1r:= v1[1..]; var v2r:= v2[1..]; var t1:= |v1[1..]|-1; var t2:= |v2[1..]|-1; // Se realiza la induccion utilizando las variables scalar_product_Lemma(v1r, v2r); assert scalar_product(v1r,v2r) == scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI // Se demuestra que la propiedad se mantiene calc{ scalar_product(v1,v2); v1[0]*v2[0] + scalar_product(v1r, v2r); v1[0]*v2[0] + scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; { scalar_product_Lemma(v1r, v2r); assert scalar_product(v1r,v2r) == scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI } v1[0]*v2[0] + scalar_product(v1r,v2r); v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]); scalar_product(v1,v2); } } } // MULTISETS method multiplicity_examples<T> () { var m := multiset{2,4,6,2,1,3,1,7,1,5,4,7,8,1,6}; assert m[7] == 2; assert m[1] == 4; assert forall m1: multiset<T>, m2 :: m1 == m2 <==> forall z:T :: m1[z] == m2[z]; } // REVERSE HAS THE SAME MULTISET lemma seqMultiset_Lemma<T> (s:seq<T>) ensures multiset(reverse(s)) == multiset(s) { if s==[]{} else { seqMultiset_Lemma(s[1..]); assert multiset(reverse(s[1..])) == multiset(s[1..]); calc { multiset(reverse(s)); multiset(reverse(s[1..]) + [s[0]]); multiset(reverse(s[1..])) + multiset{[s[0]]}; multiset(s[1..]) + multiset{[s[0]]}; multiset(s); } assert multiset(reverse(s)) == multiset(s); } } */ lemma empty_Lemma<T> (r:seq<T>) requires multiset(r) == multiset{} ensures r == [] { if r != [] { assert r[0] in multiset(r); } } lemma elem_Lemma<T> (s:seq<T>,r:seq<T>) requires s != [] && multiset(s) == multiset(r) ensures exists i :: 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); // SEQUENCES WITH EQUAL MULTISETS HAVE EQUAL SUMS lemma sumElems_Lemma(s:seq<int>, r:seq<int>) requires multiset(s) == multiset(r) ensures sum(s) == sum(r) { if s==[]{ empty_Lemma(r); } else { // Con este lema demuestro que el elemento que le quito a s tambien se lo quito a r y de esta manera // poder hacer la induccion elem_Lemma(s,r); var i :| 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); sumElems_Lemma(s[1..], r[..i]+r[i+1..]); assert sum(s[1..]) == sum(r[..i]+r[i+1..]); //HI // Hago la llamada recursiva sumElems_Lemma(s[1..], r[..i]+r[i+1..]); assert sum(s[1..]) == sum(r[..i]+r[i+1..]); calc { sum(s); s[0]+sum(s[1..]); { sumElems_Lemma(s[1..], r[..i]+r[i+1..]); assert sum(s[1..]) == sum(r[..i]+r[i+1..]); } s[0]+sum(r[..i]+r[i+1..]); { assert s[0] == r[i]; } r[i]+sum(r[..i]+r[i+1..]); { // TODO: No consigo acertarlo assume r[i]+sum(r[..i]+r[i+1..]) == sum([r[i]]+r[..i] + r[i+1..]) == sum(r); } sum(r); } } }
Formal-methods-of-software-development_tmp_tmppryvbyty_Bloque 2_Lab6.dfy
229
229
Dafny program: 229
// APELLIDOS: Heusel // NOMBRE: Benedikt // ESPECIALIDAD: ninguna (Erasmus) // ESTÁ PERFECTO, NO HAY NINGUN COMENTARIO MAS ABAJO // EJERCICIO 1 // Demostrar el lemma div10_Lemma por inducción en n // y luego usarlo para demostrar el lemma div10Forall_Lemma function exp (x:int,e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma div10_Lemma (n:nat) requires n >= 3; ensures (exp(3,4*n)+9)%10 == 0 { if n == 3 { //paso base calc { //sólo para mí, comprobado automaticamente (exp(3,4*n)+9); (exp(3,4*3)+9); exp(3, 12) + 9; 531441 + 9; 531450; 10 * 53145; } } else { //paso inductivo div10_Lemma(n-1); //assert (exp(3,4*(n-1))+9)%10 == 0; // HI var k := (exp(3,4*(n-1))+9) / 10; calc { exp(3, 4*n) + 9; 3 * 3 * exp(3,4*n - 2) + 9; 3 * 3 * 3 * 3 * exp(3,4*n - 4) + 9; 81 * exp(3,4*n - 4) + 9; 81 * exp(3,4 * (n-1)) + 9; 80 * exp(3,4 * (n-1)) + (exp(3,4 * (n-1)) + 9); 80 * exp(3,4 * (n-1)) + 10*k; 10 * (8 * exp(3,4 * (n-1)) + k); } } } //Por inducción en n lemma div10Forall_Lemma () ensures forall n :: n>=3 ==> (exp(3,4*n)+9)%10==0 { forall n | n>=3 {div10_Lemma(n);} } //Llamando al lemma anterior // EJERCICIO 2 // Demostrar por inducción en n el lemma de abajo acerca de la función sumSerie que se define primero. // Recuerda que debes JUSTIFICAR como se obtiene la propiedad del ensures a partir de la hipótesis de inducción. function sumSerie (x:int,n:nat):int { if n == 0 then 1 else sumSerie(x,n-1) + exp(x,n) } lemma {:induction false} sumSerie_Lemma (x:int,n:nat) ensures (1-x) * sumSerie(x,n) == 1 - exp(x,n+1) { if n == 0 { //paso base calc { (1-x) * sumSerie(x,n); (1-x) * sumSerie(x,0); (1-x) * 1; 1 - x; 1 - exp(x,1); 1 - exp(x,n+1); } } else{ //paso inductivo calc { (1-x) * sumSerie(x,n); (1-x) * (sumSerie(x,n-1) + exp(x,n)); (1-x) * sumSerie(x,n-1) + (1-x) * exp(x,n); { sumSerie_Lemma(x, n-1); //assert (1-x) * sumSerie(x,n-1) == 1 - exp(x,n); // HI } 1 - exp(x,n) + (1-x) * exp(x,n); 1 - exp(x,n) + exp(x,n) - x * exp(x,n); 1 - x * exp(x,n); 1 - exp(x,n + 1); } } } // EJERCICIO 3 // Probar el lemma noSq_Lemma por contradicción + casos (ver el esquema de abajo). // Se niega la propiedad en el ensures y luego se hacen dos casos (1) z%2 == 0 y (2) z%2 == 1. // En cada uno de los dos casos hay que llegar a probar "assert false" lemma notSq_Lemma (n:int) ensures !exists z :: z*z == 4*n + 2 { //Por contradicción con dos casos: if exists z :: 4*n + 2 == z*z { var z :| z*z == 4*n + 2 == z*z; if z%2 == 0 { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" var k := z/2; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k)*(2*k); 2 * (2*n+1) == 2 * (2*k*k); 2*n+1 == 2*k*k; 2*n+1 == 2*(k*k); } } else { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" //assert z % 2 == 1; var k := (z-1) / 2; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k + 1)*(2*k + 1); 4*n + 2 == 4*k*k + 4*k + 1; 4*n + 2 == 2 * (2*k*k + 2*k) + 1; 2 * (2*n + 1) == 2 * (2*k*k + 2*k) + 1; } } } } // EJERCICIO 4 //Probar el lemma oneIsEven_Lemma por contradicción, usando también el lemma del EJERCICIO 3. lemma oneIsEven_Lemma (x:int,y:int,z:int) requires z*z == x*x + y*y ensures x%2 == 0 || y%2 == 0 { if !(x%2 == 0 || y%2 == 0) { //assert x%2 == 1 && y%2 == 1; var k: int :| 2*k + 1 == x; var b: int :| 2*b + 1 == y; calc { x*x + y*y; (2*k + 1) * (2*k + 1) + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + 4*b*b + 4*b + 1; 4*k*k + 4*k + 4*b*b + 4*b + 2; 4 * (k*k + k + b*b + b) + 2; } notSq_Lemma(k*k + k + b*b + b); //assert !exists z :: z*z == 4*(k*k + k + b*b + b) + 2; } } // Por contradicción, y usando notSq_Lemma. ////////////////////////////////////////////////////////////////////////////////////////////// /* ESTE EJERCICIO SÓLO DEBES HACERLO SI HAS CONSEGUIDO DEMOSTRAR CON EXITO LOS EJERCICIOS 1 y 2 EJERCICIO 5 En este ejercicio se dan dos lemma: exp_Lemma y prod_Lemma, que Dafny demuestra automáticamente. Lo que se pide es probar expPlus1_Lemma, por inducción en n, haciendo una calculation con == y >=, que en las pistas (hints) use la HI y también llamadas a esos dos lemas. */ lemma exp_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma prod_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma expPlus1_Lemma(x:int,n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n == 1 { calc { exp(x+1,n); == exp(x+1,1); == x + 1; >= //efectivamente en el caso base tenemos igualdad x + 1; == exp(x,1) + 1; == exp(x,n) + 1; } } else { calc { exp(x+1,n); == (x + 1) * exp(x+1,n-1); >= { expPlus1_Lemma(x, n-1); //assert exp(x+1,n-1) >= exp(x,n-1) + 1; HI //assert exp(x+1,n-1) >= exp(x,n-1) + 1; // HI //aquí se necesitaría tambien prod_lemma, //pero parece que el paso se demuestra tambien //sin la llamada } (x + 1) * (exp(x,n-1) + 1); == x * exp(x,n-1) + x + exp(x,n-1) + 1; == exp(x,n) + x + exp(x,n-1) + 1; == exp(x,n) + 1 + exp(x,n-1) + x; >= { exp_Lemma(x, n-1); } exp(x,n) + 1; } } } // Por inducción en n, y usando exp_Lemma y prod_Lemma.
// APELLIDOS: Heusel // NOMBRE: Benedikt // ESPECIALIDAD: ninguna (Erasmus) // ESTÁ PERFECTO, NO HAY NINGUN COMENTARIO MAS ABAJO // EJERCICIO 1 // Demostrar el lemma div10_Lemma por inducción en n // y luego usarlo para demostrar el lemma div10Forall_Lemma function exp (x:int,e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma div10_Lemma (n:nat) requires n >= 3; ensures (exp(3,4*n)+9)%10 == 0 { if n == 3 { //paso base calc { //sólo para mí, comprobado automaticamente (exp(3,4*n)+9); (exp(3,4*3)+9); exp(3, 12) + 9; 531441 + 9; 531450; 10 * 53145; } } else { //paso inductivo div10_Lemma(n-1); //assert (exp(3,4*(n-1))+9)%10 == 0; // HI var k := (exp(3,4*(n-1))+9) / 10; assert 10 * k == (exp(3,4*(n-1))+9); calc { exp(3, 4*n) + 9; 3 * 3 * exp(3,4*n - 2) + 9; 3 * 3 * 3 * 3 * exp(3,4*n - 4) + 9; 81 * exp(3,4*n - 4) + 9; 81 * exp(3,4 * (n-1)) + 9; 80 * exp(3,4 * (n-1)) + (exp(3,4 * (n-1)) + 9); 80 * exp(3,4 * (n-1)) + 10*k; 10 * (8 * exp(3,4 * (n-1)) + k); } } } //Por inducción en n lemma div10Forall_Lemma () ensures forall n :: n>=3 ==> (exp(3,4*n)+9)%10==0 { forall n | n>=3 {div10_Lemma(n);} } //Llamando al lemma anterior // EJERCICIO 2 // Demostrar por inducción en n el lemma de abajo acerca de la función sumSerie que se define primero. // Recuerda que debes JUSTIFICAR como se obtiene la propiedad del ensures a partir de la hipótesis de inducción. function sumSerie (x:int,n:nat):int { if n == 0 then 1 else sumSerie(x,n-1) + exp(x,n) } lemma {:induction false} sumSerie_Lemma (x:int,n:nat) ensures (1-x) * sumSerie(x,n) == 1 - exp(x,n+1) { if n == 0 { //paso base calc { (1-x) * sumSerie(x,n); (1-x) * sumSerie(x,0); (1-x) * 1; 1 - x; 1 - exp(x,1); 1 - exp(x,n+1); } } else{ //paso inductivo calc { (1-x) * sumSerie(x,n); (1-x) * (sumSerie(x,n-1) + exp(x,n)); (1-x) * sumSerie(x,n-1) + (1-x) * exp(x,n); { sumSerie_Lemma(x, n-1); //assert (1-x) * sumSerie(x,n-1) == 1 - exp(x,n); // HI } 1 - exp(x,n) + (1-x) * exp(x,n); 1 - exp(x,n) + exp(x,n) - x * exp(x,n); 1 - x * exp(x,n); 1 - exp(x,n + 1); } } } // EJERCICIO 3 // Probar el lemma noSq_Lemma por contradicción + casos (ver el esquema de abajo). // Se niega la propiedad en el ensures y luego se hacen dos casos (1) z%2 == 0 y (2) z%2 == 1. // En cada uno de los dos casos hay que llegar a probar "assert false" lemma notSq_Lemma (n:int) ensures !exists z :: z*z == 4*n + 2 { //Por contradicción con dos casos: if exists z :: 4*n + 2 == z*z { var z :| z*z == 4*n + 2 == z*z; if z%2 == 0 { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" var k := z/2; assert z == 2*k; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k)*(2*k); 2 * (2*n+1) == 2 * (2*k*k); 2*n+1 == 2*k*k; 2*n+1 == 2*(k*k); } assert 0 == 2*(k*k) % 2 == (2*n+1) % 2 == 1; assert false; } else { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" //assert z % 2 == 1; var k := (z-1) / 2; assert z == 2*k + 1; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k + 1)*(2*k + 1); 4*n + 2 == 4*k*k + 4*k + 1; 4*n + 2 == 2 * (2*k*k + 2*k) + 1; 2 * (2*n + 1) == 2 * (2*k*k + 2*k) + 1; } assert 0 == (2 * (2*n + 1)) % 2 == (2 * (2*k*k + 2*k) + 1) % 2 == 1; assert false; } } } // EJERCICIO 4 //Probar el lemma oneIsEven_Lemma por contradicción, usando también el lemma del EJERCICIO 3. lemma oneIsEven_Lemma (x:int,y:int,z:int) requires z*z == x*x + y*y ensures x%2 == 0 || y%2 == 0 { if !(x%2 == 0 || y%2 == 0) { //assert x%2 == 1 && y%2 == 1; assert x == 2 * ((x-1)/2) + 1; var k: int :| 2*k + 1 == x; assert y == 2 * ((y-1)/2) + 1; var b: int :| 2*b + 1 == y; calc { x*x + y*y; (2*k + 1) * (2*k + 1) + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + 4*b*b + 4*b + 1; 4*k*k + 4*k + 4*b*b + 4*b + 2; 4 * (k*k + k + b*b + b) + 2; } assert z * z == 4 * (k*k + k + b*b + b) + 2; notSq_Lemma(k*k + k + b*b + b); //assert !exists z :: z*z == 4*(k*k + k + b*b + b) + 2; assert false; } } // Por contradicción, y usando notSq_Lemma. ////////////////////////////////////////////////////////////////////////////////////////////// /* ESTE EJERCICIO SÓLO DEBES HACERLO SI HAS CONSEGUIDO DEMOSTRAR CON EXITO LOS EJERCICIOS 1 y 2 EJERCICIO 5 En este ejercicio se dan dos lemma: exp_Lemma y prod_Lemma, que Dafny demuestra automáticamente. Lo que se pide es probar expPlus1_Lemma, por inducción en n, haciendo una calculation con == y >=, que en las pistas (hints) use la HI y también llamadas a esos dos lemas. */ lemma exp_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma prod_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma expPlus1_Lemma(x:int,n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n == 1 { calc { exp(x+1,n); == exp(x+1,1); == x + 1; >= //efectivamente en el caso base tenemos igualdad x + 1; == exp(x,1) + 1; == exp(x,n) + 1; } } else { calc { exp(x+1,n); == (x + 1) * exp(x+1,n-1); >= { expPlus1_Lemma(x, n-1); //assert exp(x+1,n-1) >= exp(x,n-1) + 1; HI //assert exp(x+1,n-1) >= exp(x,n-1) + 1; // HI //aquí se necesitaría tambien prod_lemma, //pero parece que el paso se demuestra tambien //sin la llamada } (x + 1) * (exp(x,n-1) + 1); == x * exp(x,n-1) + x + exp(x,n-1) + 1; == exp(x,n) + x + exp(x,n-1) + 1; == exp(x,n) + 1 + exp(x,n-1) + x; >= { exp_Lemma(x, n-1); } exp(x,n) + 1; } } } // Por inducción en n, y usando exp_Lemma y prod_Lemma.
Formal-methods-of-software-development_tmp_tmppryvbyty_Examenes_Beni_Heusel-Benedikt-Ass-1.dfy
230
230
Dafny program: 230
method Mult(x:nat, y:nat) returns (r:nat) ensures r == x * y { // Valores passados por parâmetros são imutáveis var m := x; var n := y; r := 0; // Soma sucessiva para multiplicar dois números. while m > 0 { r := r + n; m := m - 1; } return r; // NOT(m>0) ^ Inv ==> r = x*y } /* Inv = m*n + r = x*y Mult(5,3) Teste de mesa x y m n r Inv --> m*n + r = x*y 5 3 5 3 0 5x3+0 = 5*3 5 3 4 3 3 4x3+3 = 5*3 5 3 3 3 6 3x3+6 = 5*3 5 3 2 3 9 2x3+9 = 5*3 5 3 1 3 12 1x3+12 = 5*3 5 3 0 3 15 0x3+15 = 5*3 */
method Mult(x:nat, y:nat) returns (r:nat) ensures r == x * y { // Valores passados por parâmetros são imutáveis var m := x; var n := y; r := 0; // Soma sucessiva para multiplicar dois números. while m > 0 invariant m*n+r == x*y invariant m>=0 { r := r + n; m := m - 1; } return r; // NOT(m>0) ^ Inv ==> r = x*y } /* Inv = m*n + r = x*y Mult(5,3) Teste de mesa x y m n r Inv --> m*n + r = x*y 5 3 5 3 0 5x3+0 = 5*3 5 3 4 3 3 4x3+3 = 5*3 5 3 3 3 6 3x3+6 = 5*3 5 3 2 3 9 2x3+9 = 5*3 5 3 1 3 12 1x3+12 = 5*3 5 3 0 3 15 0x3+15 = 5*3 */
FormalMethods_tmp_tmpvda2r3_o_dafny_Invariants_ex1.dfy
231
231
Dafny program: 231
function Potencia(x:nat, y:nat):nat { if y == 0 then 1 else x * Potencia(x, y-1) } method Pot(x:nat, y:nat) returns (r:nat) ensures r == Potencia(x,y) { r := 1; var b := x; var e := y; while e > 0 { r := r * b; e := e - 1; } return r; } /* Inv = Pot(2,3) Teste de mesa x y b e r Inv --> b^e * r = x^y 2 3 2 3 1 2^3 * 2^0 = 2^3 2 3 2 2 1*2 2^2 * 2^1 = 2^3 2 3 2 1 1*2*2 2^1 * 2^2 = 2^3 2 3 2 0 1*2*2*2 2^0 * 2^3 = 2^3 */
function Potencia(x:nat, y:nat):nat { if y == 0 then 1 else x * Potencia(x, y-1) } method Pot(x:nat, y:nat) returns (r:nat) ensures r == Potencia(x,y) { r := 1; var b := x; var e := y; while e > 0 invariant Potencia(b,e) * r == Potencia(x,y) { r := r * b; e := e - 1; } return r; } /* Inv = Pot(2,3) Teste de mesa x y b e r Inv --> b^e * r = x^y 2 3 2 3 1 2^3 * 2^0 = 2^3 2 3 2 2 1*2 2^2 * 2^1 = 2^3 2 3 2 1 1*2*2 2^1 * 2^2 = 2^3 2 3 2 0 1*2*2*2 2^0 * 2^3 = 2^3 */
FormalMethods_tmp_tmpvda2r3_o_dafny_Invariants_ex2.dfy
233
233
Dafny program: 233
// A LIFO queue (aka a stack) with limited capacity. class LimitedStack{ var capacity : int; // capacity, max number of elements allowed on the stack. var arr : array<int>; // contents of stack. var top : int; // The index of the top of the stack, or -1 if the stack is empty // This predicate express a class invariant: All objects of this calls should satisfy this. predicate Valid() reads this; { arr != null && capacity > 0 && capacity == arr.Length && top >= -1 && top < capacity } predicate Empty() reads this`top; { top == -1 } predicate Full() reads this`top, this`capacity; { top == (capacity - 1) } method Init(c : int) modifies this; requires c > 0 ensures Valid() && Empty() && c == capacity ensures fresh(arr); // ensures arr is a newly created object. // Additional post-condition to be given here! { capacity := c; arr := new int[c]; top := -1; } method isEmpty() returns (res : bool) ensures res == Empty() { if(top == -1) { return true; } else { return false; } } // Returns the top element of the stack, without removing it. method Peek() returns (elem : int) requires Valid() && !Empty() ensures elem == arr[top] { return arr[top]; } // Pushed an element to the top of a (non full) stack. method Push(elem : int) modifies this`top, this.arr requires Valid() requires !Full() ensures Valid() && top == old(top) + 1 && arr[top] == elem ensures !old(Empty()) ==> forall i : int :: 0 <= i <= old(top) ==> arr[i] == old(arr[i]); { top := top + 1; arr[top] := elem; } // Pops the top element off the stack. method Pop() returns (elem : int) modifies this`top requires Valid() && !Empty() ensures Valid() && top == old(top) - 1 ensures elem == arr[old(top)] { elem := arr[top]; top := top - 1; return elem; } method Shift() requires Valid() && !Empty(); ensures Valid(); ensures forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); ensures top == old(top) - 1; modifies this.arr, this`top; { var i : int := 0; while (i < capacity - 1 ) { arr[i] := arr[i + 1]; i := i + 1; } top := top - 1; } //Push onto full stack, oldest element is discarded. method Push2(elem : int) modifies this.arr, this`top requires Valid() ensures Valid() && !Empty() ensures arr[top] == elem ensures old(!Full()) ==> top == old(top) + 1 && old(Full()) ==> top == old(top) ensures ((old(Full()) ==> arr[capacity - 1] == elem) && (old(!Full()) ==> (top == old(top) + 1 && arr[top] == elem) )) ensures old(Full()) ==> forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); { if(top == capacity - 1){ Shift(); top := top + 1; arr[top] := elem; } else{ top := top + 1; arr[top] := elem; } } // When you are finished, all the below assertions should be provable. // Feel free to add extra ones as well. method Main(){ var s := new LimitedStack; s.Init(3); s.Push(27); var e := s.Pop(); s.Push(5); s.Push(32); s.Push(9); var e2 := s.Pop(); s.Push(e2); s.Push2(99); var e3 := s.Peek(); } }
// A LIFO queue (aka a stack) with limited capacity. class LimitedStack{ var capacity : int; // capacity, max number of elements allowed on the stack. var arr : array<int>; // contents of stack. var top : int; // The index of the top of the stack, or -1 if the stack is empty // This predicate express a class invariant: All objects of this calls should satisfy this. predicate Valid() reads this; { arr != null && capacity > 0 && capacity == arr.Length && top >= -1 && top < capacity } predicate Empty() reads this`top; { top == -1 } predicate Full() reads this`top, this`capacity; { top == (capacity - 1) } method Init(c : int) modifies this; requires c > 0 ensures Valid() && Empty() && c == capacity ensures fresh(arr); // ensures arr is a newly created object. // Additional post-condition to be given here! { capacity := c; arr := new int[c]; top := -1; } method isEmpty() returns (res : bool) ensures res == Empty() { if(top == -1) { return true; } else { return false; } } // Returns the top element of the stack, without removing it. method Peek() returns (elem : int) requires Valid() && !Empty() ensures elem == arr[top] { return arr[top]; } // Pushed an element to the top of a (non full) stack. method Push(elem : int) modifies this`top, this.arr requires Valid() requires !Full() ensures Valid() && top == old(top) + 1 && arr[top] == elem ensures !old(Empty()) ==> forall i : int :: 0 <= i <= old(top) ==> arr[i] == old(arr[i]); { top := top + 1; arr[top] := elem; } // Pops the top element off the stack. method Pop() returns (elem : int) modifies this`top requires Valid() && !Empty() ensures Valid() && top == old(top) - 1 ensures elem == arr[old(top)] { elem := arr[top]; top := top - 1; return elem; } method Shift() requires Valid() && !Empty(); ensures Valid(); ensures forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); ensures top == old(top) - 1; modifies this.arr, this`top; { var i : int := 0; while (i < capacity - 1 ) invariant 0 <= i < capacity; invariant top == old(top); invariant forall j : int :: 0 <= j < i ==> arr[j] == old(arr[j + 1]); invariant forall j : int :: i <= j < capacity ==> arr[j] == old(arr[j]); { arr[i] := arr[i + 1]; i := i + 1; } top := top - 1; } //Push onto full stack, oldest element is discarded. method Push2(elem : int) modifies this.arr, this`top requires Valid() ensures Valid() && !Empty() ensures arr[top] == elem ensures old(!Full()) ==> top == old(top) + 1 && old(Full()) ==> top == old(top) ensures ((old(Full()) ==> arr[capacity - 1] == elem) && (old(!Full()) ==> (top == old(top) + 1 && arr[top] == elem) )) ensures old(Full()) ==> forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); { if(top == capacity - 1){ Shift(); top := top + 1; arr[top] := elem; } else{ top := top + 1; arr[top] := elem; } } // When you are finished, all the below assertions should be provable. // Feel free to add extra ones as well. method Main(){ var s := new LimitedStack; s.Init(3); assert s.Empty() && !s.Full(); s.Push(27); assert !s.Empty(); var e := s.Pop(); assert e == 27; assert s.top == -1; assert s.Empty() && !s.Full(); s.Push(5); assert s.top == 0; assert s.capacity == 3; s.Push(32); s.Push(9); assert s.Full(); assert s.arr[0] == 5; var e2 := s.Pop(); assert e2 == 9 && !s.Full(); assert s.arr[0] == 5; s.Push(e2); s.Push2(99); var e3 := s.Peek(); assert e3 == 99; assert s.arr[0] == 32; } }
Formal_Verification_With_Dafny_tmp_tmp5j79rq48_LimitedStack.dfy
234
234
Dafny program: 234
// Dafny verification of binary search alogirthm from binary_search.py // Inspired by: https://ece.uwaterloo.ca/~agurfink/stqam/rise4fun-Dafny/#h211 method BinarySearch(arr: array<int>, target: int) returns (index: int) requires distinct(arr) requires sorted(arr) ensures -1 <= index < arr.Length ensures index == -1 ==> not_found(arr, target) ensures index != -1 ==> found(arr, target, index) { var low, high := 0 , arr.Length-1; while low <= high { var mid := (low + high) / 2; if arr[mid] == target { return mid; } else if arr[mid] < target { low := mid + 1; } else { high := mid - 1; } } return -1; } // Predicate to check that the array is sorted predicate sorted(a: array<int>) reads a { forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] } // Predicate to that each element is unique predicate distinct(arr: array<int>) reads arr { forall i, j :: 0 <= i < arr.Length && 0 <= j < arr.Length ==> arr[i] != arr[j] } // Predicate to that the target is not in the array predicate not_found(arr: array<int>, target: int) reads arr { (forall j :: 0 <= j < arr.Length ==> arr[j] != target) } // Predicate to that the target is in the array predicate found(arr: array<int>, target: int, index: int) requires -1 <= index < arr.Length; reads arr { if index == -1 then false else if arr[index] == target then true else false }
// Dafny verification of binary search alogirthm from binary_search.py // Inspired by: https://ece.uwaterloo.ca/~agurfink/stqam/rise4fun-Dafny/#h211 method BinarySearch(arr: array<int>, target: int) returns (index: int) requires distinct(arr) requires sorted(arr) ensures -1 <= index < arr.Length ensures index == -1 ==> not_found(arr, target) ensures index != -1 ==> found(arr, target, index) { var low, high := 0 , arr.Length-1; while low <= high invariant 0 <= low <= high + 1 invariant low-1 <= high < arr.Length invariant forall i :: 0 <= i <= low && high <= i < arr.Length ==> arr[i] != target { var mid := (low + high) / 2; if arr[mid] == target { return mid; } else if arr[mid] < target { low := mid + 1; } else { high := mid - 1; } } return -1; } // Predicate to check that the array is sorted predicate sorted(a: array<int>) reads a { forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] } // Predicate to that each element is unique predicate distinct(arr: array<int>) reads arr { forall i, j :: 0 <= i < arr.Length && 0 <= j < arr.Length ==> arr[i] != arr[j] } // Predicate to that the target is not in the array predicate not_found(arr: array<int>, target: int) reads arr { (forall j :: 0 <= j < arr.Length ==> arr[j] != target) } // Predicate to that the target is in the array predicate found(arr: array<int>, target: int, index: int) requires -1 <= index < arr.Length; reads arr { if index == -1 then false else if arr[index] == target then true else false }
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Binary Search_binary_search.dfy
235
235
Dafny program: 235
// CoPilot function converted to dafny method largest_sum(nums: array<int>, k: int) returns (sum: int) requires nums.Length > 0 ensures max_sum_subarray(nums, sum, 0, nums.Length) { var max_sum := 0; var current_sum := 0; var i := 0; while (i < nums.Length) { current_sum := current_sum + nums[i]; if (current_sum > max_sum) { max_sum := current_sum; } if (current_sum < 0) { current_sum := 0; } i := i + 1; } return max_sum; } // Predicate to confirm that sum is the maximum summation of element [start, stop) predicate max_sum_subarray(arr: array<int>, sum: int, start: int, stop: int) requires arr.Length > 0 requires 0 <= start <= stop <= arr.Length reads arr { forall u, v :: start <= u < v <= stop ==> Sum_Array(arr, u, v) <= sum } //Sums array elements between [start, stop) function Sum_Array(arr: array<int>, start: int, stop: int): int requires 0 <= start <= stop <= arr.Length reads arr { if start >= stop then 0 else arr[stop-1] + Sum_Array(arr, start, stop-1) }
// CoPilot function converted to dafny method largest_sum(nums: array<int>, k: int) returns (sum: int) requires nums.Length > 0 ensures max_sum_subarray(nums, sum, 0, nums.Length) { var max_sum := 0; var current_sum := 0; var i := 0; while (i < nums.Length) invariant 0 <= i <= nums.Length invariant max_sum_subarray(nums, max_sum, 0, i) // Invariant for the max_sum invariant forall j :: 0 <= j < i ==> Sum_Array(nums, j, i) <= current_sum // Invariant for the current_sum { current_sum := current_sum + nums[i]; if (current_sum > max_sum) { max_sum := current_sum; } if (current_sum < 0) { current_sum := 0; } i := i + 1; } return max_sum; } // Predicate to confirm that sum is the maximum summation of element [start, stop) predicate max_sum_subarray(arr: array<int>, sum: int, start: int, stop: int) requires arr.Length > 0 requires 0 <= start <= stop <= arr.Length reads arr { forall u, v :: start <= u < v <= stop ==> Sum_Array(arr, u, v) <= sum } //Sums array elements between [start, stop) function Sum_Array(arr: array<int>, start: int, stop: int): int requires 0 <= start <= stop <= arr.Length decreases stop - start reads arr { if start >= stop then 0 else arr[stop-1] + Sum_Array(arr, start, stop-1) }
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Largest Sum_largest_sum.dfy
236
236
Dafny program: 236
method sortArray(arr: array<int>) returns (arr_sorted: array<int>) // Requires array length to be between 0 and 10000 requires 0 <= arr.Length < 10000 // Ensuring the arry has been sorted ensures sorted(arr_sorted, 0, arr_sorted.Length) // Ensuring that we have not modified elements but have only changed their indices ensures multiset(arr[..]) == multiset(arr_sorted[..]) // Modifies arr modifies arr { var i := 0; while i < arr.Length { var j := i; while j < arr.Length { if arr[i] > arr[j] { var temp := arr[i]; arr[i] := arr[j]; arr[j] := temp; } j := j + 1; } i := i + 1; } return arr; } // Predicate to determine whether the list is sorted between [start, stop) predicate sorted(arr: array<int>, start: int, end: int) requires 0 <= start <= end <= arr.Length reads arr { forall i, j :: start <= i <= j < end ==> arr[i] <= arr[j] } // Predicate to determine whether element arr[pivot] is a pivot point // Based on: https://github.com/stqam/dafny/blob/master/BubbleSort.dfy predicate pivot(arr: array<int>, pivot: int) requires 0 <= pivot <= arr.Length reads arr { forall u, v :: 0 <= u < pivot < v < arr.Length ==> arr[u] <= arr[v] }
method sortArray(arr: array<int>) returns (arr_sorted: array<int>) // Requires array length to be between 0 and 10000 requires 0 <= arr.Length < 10000 // Ensuring the arry has been sorted ensures sorted(arr_sorted, 0, arr_sorted.Length) // Ensuring that we have not modified elements but have only changed their indices ensures multiset(arr[..]) == multiset(arr_sorted[..]) // Modifies arr modifies arr { var i := 0; while i < arr.Length invariant i <= arr.Length invariant sorted(arr, 0, i) invariant multiset(old(arr[..])) == multiset(arr[..]) invariant forall u, v :: 0 <= u < i && i <= v < arr.Length ==> arr[u] <= arr[v] invariant pivot(arr, i) { var j := i; while j < arr.Length invariant j <= arr.Length invariant multiset(old(arr[..])) == multiset(arr[..]) invariant pivot(arr, i) invariant forall u :: i < u < j ==> arr[i] <= arr[u] invariant forall u :: 0 <= u < i ==> arr[u] <= arr[i] invariant sorted(arr, 0, i+1) { if arr[i] > arr[j] { var temp := arr[i]; arr[i] := arr[j]; arr[j] := temp; } j := j + 1; } i := i + 1; } return arr; } // Predicate to determine whether the list is sorted between [start, stop) predicate sorted(arr: array<int>, start: int, end: int) requires 0 <= start <= end <= arr.Length reads arr { forall i, j :: start <= i <= j < end ==> arr[i] <= arr[j] } // Predicate to determine whether element arr[pivot] is a pivot point // Based on: https://github.com/stqam/dafny/blob/master/BubbleSort.dfy predicate pivot(arr: array<int>, pivot: int) requires 0 <= pivot <= arr.Length reads arr { forall u, v :: 0 <= u < pivot < v < arr.Length ==> arr[u] <= arr[v] }
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Sort Array_sort_array.dfy
237
237
Dafny program: 237
method twoSum(nums: array<int>, target: int) returns (index1: int, index2: int) requires 2 <= nums.Length requires exists i, j :: (0 <= i < j < nums.Length && nums[i] + nums[j] == target) ensures index1 != index2 ensures 0 <= index1 < nums.Length ensures 0 <= index2 < nums.Length ensures nums[index1] + nums[index2] == target { var i := 0; while i < nums.Length { var j := i + 1; while j < nums.Length { if nums[i] + nums[j] == target { return i, j; } j := j + 1; } i := i + 1; } }
method twoSum(nums: array<int>, target: int) returns (index1: int, index2: int) requires 2 <= nums.Length requires exists i, j :: (0 <= i < j < nums.Length && nums[i] + nums[j] == target) ensures index1 != index2 ensures 0 <= index1 < nums.Length ensures 0 <= index2 < nums.Length ensures nums[index1] + nums[index2] == target { var i := 0; while i < nums.Length invariant 0 <= i < nums.Length invariant forall u, v :: 0 <= u < v < nums.Length && u < i ==> nums[u] + nums[v] != target invariant exists u, v :: i <= u < v < nums.Length && nums[u] + nums[v] == target { var j := i + 1; while j < nums.Length invariant 0 <= i < j <= nums.Length invariant forall u, v :: 0 <= u < v < nums.Length && u < i ==> nums[u] + nums[v] != target invariant exists u, v :: i <= u < v < nums.Length && nums[u] + nums[v] == target invariant forall u :: i < u < j ==> nums[i] + nums[u] != target { if nums[i] + nums[j] == target { return i, j; } j := j + 1; } i := i + 1; } }
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Two Sum_two_sum.dfy
238
238
Dafny program: 238
module Ints { const U32_BOUND: nat := 0x1_0000_0000 newtype u32 = x:int | 0 <= x < 0x1_0000_0000 newtype i32 = x: int | -0x8000_0000 <= x < 0x8000_0000 } module Lang { import opened Ints datatype Reg = R0 | R1 | R2 | R3 datatype Expr = | Const(n: u32) // overflow during addition is an error | Add(r1: Reg, r2: Reg) // this is saturating subtraction (to allow comparing numbers) | Sub(r1: Reg, r2: Reg) datatype Stmt = | Assign(r: Reg, e: Expr) // Jump by offset if condition is true | JmpZero(r: Reg, offset: i32) datatype Program = Program(stmts: seq<Stmt>) } /* Well-formed check: offsets are all within the program */ /* Main safety property: additions do not overflow */ /* First, we give the concrete semantics of programs. */ module ConcreteEval { import opened Ints import opened Lang type State = Reg -> u32 function update_state(s: State, r0: Reg, v: u32): State { ((r: Reg) => if r == r0 then v else s(r)) } datatype Option<T> = Some(v: T) | None function expr_eval(env: State, e: Expr): Option<u32> { match e { case Const(n) => Some(n) case Add(r1, r2) => (if (env(r1) as int + env(r2) as int >= U32_BOUND) then None else Some(env(r1) + env(r2))) case Sub(r1, r2) => (if env(r1) as int - env(r2) as int < 0 then Some(0) else Some(env(r1) - env(r2))) } } // stmt_step executes a single statement // // Returns a new state and a relative PC offset (which is 1 for non-jump // statements). function stmt_step(env: State, s: Stmt): Option<(State, int)> { match s { case Assign(r, e) => var e' := expr_eval(env, e); match e' { case Some(v) => Some((update_state(env, r, v), 1)) case None => None } case JmpZero(r, offset) => Some((env, (if env(r) == 0 then offset else 1) as int)) } } datatype ExecResult = Ok(env: State) | NoFuel | Error // Run a program starting at pc. // // The sequence of statements is constant, meant to reflect a static program. // Termination occurs if the pc ever reaches exactly the end. // // Errors can come from either executing statements (see stmt_step for those // errors), or from an out-of-bounds pc (negative or not past the end of ss). // // fuel is needed to make this function terminate; the idea is that if there // exists some fuel that makes the program terminate, that is it's complete // execution, and if it always runs out of fuel it has an infinite loop. function stmts_step(env: State, ss: seq<Stmt>, pc: nat, fuel: nat): ExecResult requires pc <= |ss| { if fuel == 0 then NoFuel else if pc == |ss| then Ok(env) else match stmt_step(env, ss[pc]) { case None => Error case Some((env', offset)) => if !(0 <= pc + offset <= |ss|) then Error else stmts_step(env', ss, pc + offset, fuel - 1) } } } /* Now we turn to analyzing programs */ module AbstractEval { import opened Ints import opened Lang datatype Val = Interval(lo: int, hi: int) datatype AbstractState = AbstractState(rs: Reg -> Val) function expr_eval(env: AbstractState, e: Expr): Val { match e { case Const(n) => Interval(n as int, n as int) case Add(r1, r2) => var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(v1.lo + v2.lo, v1.hi + v2.hi) case Sub(r1, r2) => // this was quite buggy initially: low is bounded (due to saturating // subtraction), and upper bound also should cannot go negative var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(0, if v1.hi - v2.lo >= 0 then v1.hi - v2.lo else 0) } } function update_state(env: AbstractState, r0: Reg, v: Val): AbstractState { AbstractState((r: Reg) => if r == r0 then v else env.rs(r)) } // function stmt_step(env: State, s: Stmt): Option<(State, int)> function stmt_eval(env: AbstractState, s: Stmt): (AbstractState, set<int>) { match s { case Assign(r, e) => var v := expr_eval(env, e); (update_state(env, r, v), {1 as int}) case JmpZero(r, offset) => // imprecise analysis: we don't try to prove that this jump is or isn't taken (env, {offset as int, 1}) } } /* TODO(tej): to interpret a program, we need to explore all paths. Along the * way, we would have to look for loops - our plan is to disallow them (unlike * a normal abstract interpretation which would try to run till a fixpoint). */ // Implement a check for just the jump targets, which are static and thus // don't even need abstract interpretation. // Check that jump targets ss[from..] are valid. function has_valid_jump_targets(ss: seq<Stmt>, from: nat): bool requires from <= |ss| { if from == |ss| then true else (match ss[from] { case JmpZero(_, offset) => 0 <= from + offset as int <= |ss| case _ => true } && has_valid_jump_targets(ss, from+1)) } ghost predicate valid_jump_targets(ss: seq<Stmt>) { forall i | 0 <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss| } lemma has_valid_jump_targets_ok_helper(ss: seq<Stmt>, from: nat) requires from <= |ss| ensures has_valid_jump_targets(ss, from) <==> (forall i | from <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|) { } lemma has_valid_jump_targets_ok(ss: seq<Stmt>) ensures has_valid_jump_targets(ss, 0) <==> valid_jump_targets(ss) { has_valid_jump_targets_ok_helper(ss, 0); } } module AbstractEvalProof { import opened Ints import opened Lang import E = ConcreteEval import opened AbstractEval /* What does it mean for a concrete state to be captured by an abstract state? * (Alternately, interpret each abstract state as a set of concrete states) */ ghost predicate reg_included(c_v: u32, v: Val) { v.lo <= c_v as int <= v.hi } ghost predicate state_included(env: E.State, abs: AbstractState) { forall r: Reg :: reg_included(env(r), abs.rs(r)) } lemma expr_eval_ok(env: E.State, abs: AbstractState, e: Expr) requires state_included(env, abs) requires E.expr_eval(env, e).Some? ensures reg_included(E.expr_eval(env, e).v, expr_eval(abs, e)) { match e { case Add(_, _) => { return; } case Const(_) => { return; } case Sub(r1, r2) => { /* debugging bug in the abstract interpretation */ if env(r1) <= env(r2) { return; } return; } } } lemma stmt_eval_ok(env: E.State, abs: AbstractState, stmt: Stmt) requires state_included(env, abs) requires E.stmt_step(env, stmt).Some? ensures state_included(E.stmt_step(env, stmt).v.0, stmt_eval(abs, stmt).0) {} }
module Ints { const U32_BOUND: nat := 0x1_0000_0000 newtype u32 = x:int | 0 <= x < 0x1_0000_0000 newtype i32 = x: int | -0x8000_0000 <= x < 0x8000_0000 } module Lang { import opened Ints datatype Reg = R0 | R1 | R2 | R3 datatype Expr = | Const(n: u32) // overflow during addition is an error | Add(r1: Reg, r2: Reg) // this is saturating subtraction (to allow comparing numbers) | Sub(r1: Reg, r2: Reg) datatype Stmt = | Assign(r: Reg, e: Expr) // Jump by offset if condition is true | JmpZero(r: Reg, offset: i32) datatype Program = Program(stmts: seq<Stmt>) } /* Well-formed check: offsets are all within the program */ /* Main safety property: additions do not overflow */ /* First, we give the concrete semantics of programs. */ module ConcreteEval { import opened Ints import opened Lang type State = Reg -> u32 function update_state(s: State, r0: Reg, v: u32): State { ((r: Reg) => if r == r0 then v else s(r)) } datatype Option<T> = Some(v: T) | None function expr_eval(env: State, e: Expr): Option<u32> { match e { case Const(n) => Some(n) case Add(r1, r2) => (if (env(r1) as int + env(r2) as int >= U32_BOUND) then None else Some(env(r1) + env(r2))) case Sub(r1, r2) => (if env(r1) as int - env(r2) as int < 0 then Some(0) else Some(env(r1) - env(r2))) } } // stmt_step executes a single statement // // Returns a new state and a relative PC offset (which is 1 for non-jump // statements). function stmt_step(env: State, s: Stmt): Option<(State, int)> { match s { case Assign(r, e) => var e' := expr_eval(env, e); match e' { case Some(v) => Some((update_state(env, r, v), 1)) case None => None } case JmpZero(r, offset) => Some((env, (if env(r) == 0 then offset else 1) as int)) } } datatype ExecResult = Ok(env: State) | NoFuel | Error // Run a program starting at pc. // // The sequence of statements is constant, meant to reflect a static program. // Termination occurs if the pc ever reaches exactly the end. // // Errors can come from either executing statements (see stmt_step for those // errors), or from an out-of-bounds pc (negative or not past the end of ss). // // fuel is needed to make this function terminate; the idea is that if there // exists some fuel that makes the program terminate, that is it's complete // execution, and if it always runs out of fuel it has an infinite loop. function stmts_step(env: State, ss: seq<Stmt>, pc: nat, fuel: nat): ExecResult requires pc <= |ss| decreases fuel { if fuel == 0 then NoFuel else if pc == |ss| then Ok(env) else match stmt_step(env, ss[pc]) { case None => Error case Some((env', offset)) => if !(0 <= pc + offset <= |ss|) then Error else stmts_step(env', ss, pc + offset, fuel - 1) } } } /* Now we turn to analyzing programs */ module AbstractEval { import opened Ints import opened Lang datatype Val = Interval(lo: int, hi: int) datatype AbstractState = AbstractState(rs: Reg -> Val) function expr_eval(env: AbstractState, e: Expr): Val { match e { case Const(n) => Interval(n as int, n as int) case Add(r1, r2) => var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(v1.lo + v2.lo, v1.hi + v2.hi) case Sub(r1, r2) => // this was quite buggy initially: low is bounded (due to saturating // subtraction), and upper bound also should cannot go negative var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(0, if v1.hi - v2.lo >= 0 then v1.hi - v2.lo else 0) } } function update_state(env: AbstractState, r0: Reg, v: Val): AbstractState { AbstractState((r: Reg) => if r == r0 then v else env.rs(r)) } // function stmt_step(env: State, s: Stmt): Option<(State, int)> function stmt_eval(env: AbstractState, s: Stmt): (AbstractState, set<int>) { match s { case Assign(r, e) => var v := expr_eval(env, e); (update_state(env, r, v), {1 as int}) case JmpZero(r, offset) => // imprecise analysis: we don't try to prove that this jump is or isn't taken (env, {offset as int, 1}) } } /* TODO(tej): to interpret a program, we need to explore all paths. Along the * way, we would have to look for loops - our plan is to disallow them (unlike * a normal abstract interpretation which would try to run till a fixpoint). */ // Implement a check for just the jump targets, which are static and thus // don't even need abstract interpretation. // Check that jump targets ss[from..] are valid. function has_valid_jump_targets(ss: seq<Stmt>, from: nat): bool decreases |ss|-from requires from <= |ss| { if from == |ss| then true else (match ss[from] { case JmpZero(_, offset) => 0 <= from + offset as int <= |ss| case _ => true } && has_valid_jump_targets(ss, from+1)) } ghost predicate valid_jump_targets(ss: seq<Stmt>) { forall i | 0 <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss| } lemma has_valid_jump_targets_ok_helper(ss: seq<Stmt>, from: nat) requires from <= |ss| decreases |ss|-from ensures has_valid_jump_targets(ss, from) <==> (forall i | from <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|) { } lemma has_valid_jump_targets_ok(ss: seq<Stmt>) ensures has_valid_jump_targets(ss, 0) <==> valid_jump_targets(ss) { has_valid_jump_targets_ok_helper(ss, 0); } } module AbstractEvalProof { import opened Ints import opened Lang import E = ConcreteEval import opened AbstractEval /* What does it mean for a concrete state to be captured by an abstract state? * (Alternately, interpret each abstract state as a set of concrete states) */ ghost predicate reg_included(c_v: u32, v: Val) { v.lo <= c_v as int <= v.hi } ghost predicate state_included(env: E.State, abs: AbstractState) { forall r: Reg :: reg_included(env(r), abs.rs(r)) } lemma expr_eval_ok(env: E.State, abs: AbstractState, e: Expr) requires state_included(env, abs) requires E.expr_eval(env, e).Some? ensures reg_included(E.expr_eval(env, e).v, expr_eval(abs, e)) { match e { case Add(_, _) => { return; } case Const(_) => { return; } case Sub(r1, r2) => { /* debugging bug in the abstract interpretation */ assert reg_included(env(r1), abs.rs(r1)); assert reg_included(env(r2), abs.rs(r2)); assert env(r1) as int <= abs.rs(r1).hi; assert env(r2) as int >= abs.rs(r2).lo; if env(r1) <= env(r2) { assert E.expr_eval(env, e).v == 0; return; } assert E.expr_eval(env, e).v as int == env(r1) as int - env(r2) as int; return; } } } lemma stmt_eval_ok(env: E.State, abs: AbstractState, stmt: Stmt) requires state_included(env, abs) requires E.stmt_step(env, stmt).Some? ensures state_included(E.stmt_step(env, stmt).v.0, stmt_eval(abs, stmt).0) {} }
Invoker_tmp_tmpypx0gs8x_dafny_abstract-interpreter_SimpleVerifier.dfy
239
239
Dafny program: 239
method CountToAndReturnN(n: int) returns (r: int) requires n >= 0 ensures r == n { var i := 0; while i < n { i := i + 1; } r := i; }
method CountToAndReturnN(n: int) returns (r: int) requires n >= 0 ensures r == n { var i := 0; while i < n invariant 0 <= i <= n { i := i + 1; } r := i; }
M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo4-CountAndReturn.dfy
240
240
Dafny program: 240
function Sum(n:nat):nat { if n==0 then 0 else n + Sum(n-1) } method ComputeSum(n:nat) returns (s:nat) ensures s ==Sum(n) { s := 0; var i := 0; while i< n { s := s + i + 1; i := i+1; } }
function Sum(n:nat):nat { if n==0 then 0 else n + Sum(n-1) } method ComputeSum(n:nat) returns (s:nat) ensures s ==Sum(n) { s := 0; var i := 0; while i< n invariant 0 <= i <= n invariant s == Sum(i) { s := s + i + 1; i := i+1; } }
M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo7-ComputeSum.dfy
241
241
Dafny program: 241
method Carre(a: nat) returns (c: nat) ensures c == a*a { var i := 0; c := 0; while i != a { c := c + 2*i +1; i := i + 1; } }
method Carre(a: nat) returns (c: nat) ensures c == a*a { var i := 0; c := 0; while i != a invariant 0 <= i <= a invariant c == i*i decreases a - i { c := c + 2*i +1; i := i + 1; } }
M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo9-Carre.dfy
242
242
Dafny program: 242
// Ejercicio 1: Demostrar por inducci�n el siguiente lema: lemma EcCuadDiv2_Lemma (x:int) requires x >= 1 ensures (x*x + x) % 2 == 0 { if x != 1 { EcCuadDiv2_Lemma(x-1); } } // Ejercicio 2: Demostrar por inducci�n el siguiente lema // Indicaciones: (1) Puedes llamar al lema del ejercicio anterior, si lo necesitas. // (2) Recuerda que, a veces, simplificar la HI puede ayudar a saber donde utilizarla. lemma EcCubicaDiv6_Lemma (x:int) requires x >= 1 ensures (x*x*x + 3*x*x + 2*x) % 6 == 0 { if x>1 { EcCubicaDiv6_Lemma(x-1); //assert ((x-1)*(x-1)*(x-1) + 3*(x-1)*(x-1) + 2*(x-1)) % 6 == 0; //HI EcCuadDiv2_Lemma(x); } } // Ejercicio 3: Probar por contradicci�n el siguiente lemma: lemma cubEven_Lemma (x:int) requires (x*x*x + 5) % 2 == 1 ensures x % 2 == 0 { if x%2 == 1 { var k := (x-1)/2; == 8*k*k*k + 12*k*k + 6*k + 6 == 2*(4*k*k*k + 6*k*k + 3*k + 3); } } // Ejercicio 4: Prueba el siguiente lemma por casos (de acuerdo a los tres valores posibles de x%3) lemma perfectCube_Lemma (x:int) ensures exists z :: (x*x*x == 3*z || x*x*x == 3*z + 1 || x*x*x == 3*z - 1); { if x%3 == 0 { var k := x/3; } else if x%3 == 1 { var k := (x-1)/3; } else { var k := (x-2)/3; } } // Ejercicio 5: Dada la siguiente funci�n exp y los dos lemmas expGET1_Lemma y prodMon_Lemma (que Dafny demuestra autom�ticamente) // demostrar el lemma expMon_Lemma por inducci�n en n. Usar calc {} y poner como "hints" las llamadas a los lemmas en los // pasos del c�lculo donde son utilizadas. function exp(x:int, e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma expGET1_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} lemma prodMon_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} lemma expMon_Lemma(x:int, n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n != 1 { calc { exp(x+1,n); == (x+1)*exp(x+1,n-1); == x*exp(x+1,n-1) + exp(x+1,n-1); >= { expGET1_Lemma(x+1,n-1); } x*exp(x+1,n-1); >= { expMon_Lemma(x,n-1); //assert exp(x+1,n-1) >= (exp(x,n-1) + 1); expGET1_Lemma(x+1,n-1); //assert exp(x+1,n-1) >= 1; expGET1_Lemma(x,n-1); //assert (exp(x,n-1) + 1) >= 1; prodMon_Lemma(x, exp(x+1,n-1), exp(x,n-1) + 1); //assert x*exp(x+1,n-1) >= x*(exp(x,n-1) + 1); } x*(exp(x,n-1) + 1); == x*exp(x,n-1) + x; >= exp(x,n)+1; } } }
// Ejercicio 1: Demostrar por inducci�n el siguiente lema: lemma EcCuadDiv2_Lemma (x:int) requires x >= 1 ensures (x*x + x) % 2 == 0 { if x != 1 { EcCuadDiv2_Lemma(x-1); assert x*x+x == ((x-1)*(x-1) + (x-1)) + 2*x; } } // Ejercicio 2: Demostrar por inducci�n el siguiente lema // Indicaciones: (1) Puedes llamar al lema del ejercicio anterior, si lo necesitas. // (2) Recuerda que, a veces, simplificar la HI puede ayudar a saber donde utilizarla. lemma EcCubicaDiv6_Lemma (x:int) requires x >= 1 ensures (x*x*x + 3*x*x + 2*x) % 6 == 0 { if x>1 { EcCubicaDiv6_Lemma(x-1); //assert ((x-1)*(x-1)*(x-1) + 3*(x-1)*(x-1) + 2*(x-1)) % 6 == 0; //HI assert (x*x*x - 3*x*x + 3*x -1 + 3*x*x - 6*x + 3 + 2*x -2) % 6 == 0; //HI assert (x*x*x - x) % 6 == 0; //HI assert x*x*x + 3*x*x + 2*x == (x*x*x - x) + 3*(x*x + x); EcCuadDiv2_Lemma(x); } } // Ejercicio 3: Probar por contradicci�n el siguiente lemma: lemma cubEven_Lemma (x:int) requires (x*x*x + 5) % 2 == 1 ensures x % 2 == 0 { if x%2 == 1 { var k := (x-1)/2; assert x*x*x + 5 == (2*k+1)*(2*k+1)*(2*k+1) + 5 == 8*k*k*k + 12*k*k + 6*k + 6 == 2*(4*k*k*k + 6*k*k + 3*k + 3); assert false; } } // Ejercicio 4: Prueba el siguiente lemma por casos (de acuerdo a los tres valores posibles de x%3) lemma perfectCube_Lemma (x:int) ensures exists z :: (x*x*x == 3*z || x*x*x == 3*z + 1 || x*x*x == 3*z - 1); { if x%3 == 0 { var k := x/3; assert x*x*x == 27*k*k*k == 3*(9*k*k*k); } else if x%3 == 1 { var k := (x-1)/3; assert x*x*x == (3*k+1)*(3*k+1)*(3*k+1) == 27*k*k*k + 27*k*k + 9*k + 1; assert x*x*x == 3*(9*k*k*k + 9*k*k + 3*k) + 1; } else { var k := (x-2)/3; assert x*x*x == (3*k+2)*(3*k+2)*(3*k+2) == 27*k*k*k + 54*k*k + 36*k + 8; assert x*x*x == 3*(9*k*k*k + 18*k*k + 12*k + 3) - 1; } } // Ejercicio 5: Dada la siguiente funci�n exp y los dos lemmas expGET1_Lemma y prodMon_Lemma (que Dafny demuestra autom�ticamente) // demostrar el lemma expMon_Lemma por inducci�n en n. Usar calc {} y poner como "hints" las llamadas a los lemmas en los // pasos del c�lculo donde son utilizadas. function exp(x:int, e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma expGET1_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} lemma prodMon_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} lemma expMon_Lemma(x:int, n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n != 1 { calc { exp(x+1,n); == (x+1)*exp(x+1,n-1); == x*exp(x+1,n-1) + exp(x+1,n-1); >= { expGET1_Lemma(x+1,n-1); } x*exp(x+1,n-1); >= { expMon_Lemma(x,n-1); //assert exp(x+1,n-1) >= (exp(x,n-1) + 1); expGET1_Lemma(x+1,n-1); //assert exp(x+1,n-1) >= 1; expGET1_Lemma(x,n-1); //assert (exp(x,n-1) + 1) >= 1; prodMon_Lemma(x, exp(x+1,n-1), exp(x,n-1) + 1); //assert x*exp(x+1,n-1) >= x*(exp(x,n-1) + 1); } x*(exp(x,n-1) + 1); == x*exp(x,n-1) + x; >= exp(x,n)+1; } } }
MFDS_tmp_tmpvvr5y1t9_Assignments_Ass-1-2020-21-Sol-eGela.dfy
243
243
Dafny program: 243
function C(n: nat): nat { if n == 0 then 1 else (4 * n - 2) * C(n-1) / (n + 1) } method calcC(n: nat) returns (res: nat) ensures res == C(n) { var i := 0; res := 1; while i < n { ghost var v0 := n - i; i := i + 1; res := (4 * i - 2) * res / (i + 1); } }
function C(n: nat): nat decreases n { if n == 0 then 1 else (4 * n - 2) * C(n-1) / (n + 1) } method calcC(n: nat) returns (res: nat) ensures res == C(n) { var i := 0; res := 1; assert res == C(i) && 0 <= i <= n; while i < n decreases n - i //a - loop variant invariant res == C(i) && 0 <= i <= n //b - loop invariant { ghost var v0 := n - i; assert res == C(i) && 0 <= i <= n && i < n && n - i == v0; i := i + 1; res := (4 * i - 2) * res / (i + 1); assert res == C(i) && 0 <= i <= n && 0 <= n - i < v0; } assert res == C(i) && 0 <= i <= n && i >= n; }
MFES_2021_tmp_tmpuljn8zd9_Exams_Special_Exam_03_2020_4_CatalanNumbers.dfy
244
244
Dafny program: 244
method find(a: array<int>, key: int) returns(index: int) requires a.Length > 0; ensures 0 <= index <= a.Length; ensures index < a.Length ==> a[index] == key; { index := 0; while index < a.Length && a[index] != key { index := index + 1; } }
method find(a: array<int>, key: int) returns(index: int) requires a.Length > 0; ensures 0 <= index <= a.Length; ensures index < a.Length ==> a[index] == key; { index := 0; while index < a.Length && a[index] != key decreases a.Length - index invariant 0 <= index <= a.Length invariant forall x :: 0 <= x < index ==> a[x] != key { index := index + 1; } }
MFES_2021_tmp_tmpuljn8zd9_FCUL_Exercises_10_find.dfy
245
245
Dafny program: 245
function calcSum(n: nat) : nat { n * (n - 1) / 2 } method sum(n: nat) returns(s: nat) ensures s == calcSum(n + 1) { s := 0; var i := 0; while i < n { i := i + 1; s := s + i; } }
function calcSum(n: nat) : nat { n * (n - 1) / 2 } method sum(n: nat) returns(s: nat) ensures s == calcSum(n + 1) { s := 0; var i := 0; while i < n decreases n - i invariant 0 <= i <= n invariant s == calcSum(i + 1) { i := i + 1; s := s + i; } }
MFES_2021_tmp_tmpuljn8zd9_FCUL_Exercises_8_sum.dfy
246
246
Dafny program: 246
// Sorts array 'a' using the insertion sort algorithm. method insertionSort(a: array<int>) modifies a ensures isSorted(a, 0, a.Length) ensures multiset(a[..]) == multiset(old(a[..])) { var i := 0; while i < a.Length { var j := i; while j > 0 && a[j-1] > a[j] { a[j-1], a[j] := a[j], a[j-1]; j := j - 1; } i := i + 1; } } // Checks if array 'a' is sorted. predicate isSorted(a: array<int>, from: nat, to: nat) reads a requires 0 <= from <= to <= a.Length { forall i, j :: from <= i < j < to ==> a[i] <= a[j] } // Simple test case to check the postcondition method testInsertionSort() { var a := new int[] [ 9, 4, 3, 6, 8]; insertionSort(a); }
// Sorts array 'a' using the insertion sort algorithm. method insertionSort(a: array<int>) modifies a ensures isSorted(a, 0, a.Length) ensures multiset(a[..]) == multiset(old(a[..])) { var i := 0; while i < a.Length decreases a.Length - i invariant 0 <= i <= a.Length invariant isSorted(a, 0, i) invariant multiset(a[..]) == multiset(old(a[..])) { var j := i; while j > 0 && a[j-1] > a[j] decreases j invariant 0 <= j <= i invariant multiset(a[..]) == multiset(old(a[..])) invariant forall l, r :: 0 <= l < r <= i && r != j ==> a[l] <= a[r] { a[j-1], a[j] := a[j], a[j-1]; j := j - 1; } i := i + 1; } } // Checks if array 'a' is sorted. predicate isSorted(a: array<int>, from: nat, to: nat) reads a requires 0 <= from <= to <= a.Length { forall i, j :: from <= i < j < to ==> a[i] <= a[j] } // Simple test case to check the postcondition method testInsertionSort() { var a := new int[] [ 9, 4, 3, 6, 8]; assert a[..] == [9, 4, 3, 6, 8]; insertionSort(a); assert a[..] == [3, 4, 6, 8, 9]; }
MFES_2021_tmp_tmpuljn8zd9_PracticalClasses_TP3_2_Insertion_Sort.dfy
247
247
Dafny program: 247
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, MIEIC, MFES, 2020/21. */ // Initial specification/definition of x^n, recursive, 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) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(x: real, n: nat) returns (p : real) ensures p == power(x, n) { // start with p = x^0 var i := 0; p := 1.0; // x ^ i // iterate until reaching p = x^n while i < n { p := p * x; i := i + 1; } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(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 { distributiveProperty(x, n/2, n/2); // recall lemma here var temp := powerOpt(x, n/2); return temp * temp; } else { distributiveProperty(x, (n-1)/2, (n-1)/2); // recall lemma here var temp := powerOpt(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that powerOpt takes advantage of. // The annotation {:induction a} guides Dafny to prove the property // by automatic induction on 'a'. lemma {:induction a} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { // // To use the proof below, deactivate automatic induction, with {:induction false}. /* if a == 0 { // base case calc == { power(x, a) * power(x, b); power(x, 0) * power(x, b); // substitution 1.0 * power(x, b); // by the definition of power power(x, b); // neutral element of "*" power(x, a + b); // neutral element of "+" } } else { // recursive case, assuming property holds for a-1 (proof by induction) distributiveProperty(x, a-1, b); // now do the proof calc == { power(x, a) * power(x, b); (x * power(x, a-1)) * power(x, b); // by the definition of power x * (power(x, a-1) * power(x, b)); // associative property x * power(x, a + b - 1); // this same property for a-1 power(x, a + b); // definition of power } }*/ } // A simple test case to make sure the specification is adequate. method testPowerIter(){ var p1 := powerIter(2.0, 5); } method testPowerOpt(){ var p1 := powerOpt(2.0, 5); }
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, MIEIC, MFES, 2020/21. */ // Initial specification/definition of x^n, recursive, functional style, // with time and space complexity O(n). function power(x: real, n: nat) : real decreases n { if n == 0 then 1.0 else x * power(x, n-1) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(x: real, n: nat) returns (p : real) ensures p == power(x, n) { // start with p = x^0 var i := 0; p := 1.0; // x ^ i // iterate until reaching p = x^n while i < n decreases n - i invariant 0 <= i <= n && p == power(x, i) { p := p * x; i := i + 1; } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(x: real, n: nat) returns (p : real) ensures p == power(x, n); decreases n; { if n == 0 { return 1.0; } else if n == 1 { return x; } else if n % 2 == 0 { distributiveProperty(x, n/2, n/2); // recall lemma here var temp := powerOpt(x, n/2); return temp * temp; } else { distributiveProperty(x, (n-1)/2, (n-1)/2); // recall lemma here var temp := powerOpt(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that powerOpt takes advantage of. // The annotation {:induction a} guides Dafny to prove the property // by automatic induction on 'a'. lemma {:induction a} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { // // To use the proof below, deactivate automatic induction, with {:induction false}. /* if a == 0 { // base case calc == { power(x, a) * power(x, b); power(x, 0) * power(x, b); // substitution 1.0 * power(x, b); // by the definition of power power(x, b); // neutral element of "*" power(x, a + b); // neutral element of "+" } } else { // recursive case, assuming property holds for a-1 (proof by induction) distributiveProperty(x, a-1, b); // now do the proof calc == { power(x, a) * power(x, b); (x * power(x, a-1)) * power(x, b); // by the definition of power x * (power(x, a-1) * power(x, b)); // associative property x * power(x, a + b - 1); // this same property for a-1 power(x, a + b); // definition of power } }*/ } // A simple test case to make sure the specification is adequate. method testPowerIter(){ var p1 := powerIter(2.0, 5); assert p1 == 32.0; } method testPowerOpt(){ var p1 := powerOpt(2.0, 5); assert p1 == 32.0; }
MFES_2021_tmp_tmpuljn8zd9_TheoreticalClasses_Power.dfy
248
248
Dafny program: 248
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, M.EIC, MFS, 2021/22. */ // Initial specification/definition of x^n, recursive, 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) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(b: real, n: nat) returns (p : real) ensures p == power(b, n) { // start with p = b^0 p := 1.0; var i := 0; // iterate until reaching p = b^n while i < n { p := p * b; i := i + 1; } } lemma {:induction e1} powDist(b: real, e1: nat, e2: nat) ensures power(b, e1+e2) == power(b, e1) * power(b, e2) {} lemma {:induction false} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a+b) { if a == 0 { power(x, a) * power(x, b) == 1.0 * power(x, b) == power(x, b) == power(x, a + b); } else { distributiveProperty(x, a-1, b); power(x, a) * power(x, b) == (x * power(x, a-1)) * power(x, b) == x * (power(x, a-1) * power(x, b)) == x * power(x, a - 1 + b) == power(x, a + b); } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(b: real, n: nat) returns (p : real) ensures p == power(b, n) { if n == 0 { return 1.0; } else if n % 2 == 0 { distributiveProperty(b, n/2, n/2); var r := powerOpt(b, n/2); return r * r; } else { distributiveProperty(b, (n-1)/2, (n-1)/2); var r := powerOpt(b, (n-1)/2); return r * r * b; } } // A simple test case to make sure the specification is adequate. method testPower() { var p1 := powerIter(2.0, 5); var p2 := powerOpt(2.0, 5); print "P1: ", p1, "\n"; print "P2: ", p2, "\n"; }
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, M.EIC, MFS, 2021/22. */ // Initial specification/definition of x^n, recursive, 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) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(b: real, n: nat) returns (p : real) ensures p == power(b, n) { // start with p = b^0 p := 1.0; var i := 0; // iterate until reaching p = b^n while i < n invariant p == power(b, i) && 0 <= i <= n { p := p * b; i := i + 1; } } lemma {:induction e1} powDist(b: real, e1: nat, e2: nat) ensures power(b, e1+e2) == power(b, e1) * power(b, e2) {} lemma {:induction false} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a+b) { if a == 0 { assert power(x, a) * power(x, b) == 1.0 * power(x, b) == power(x, b) == power(x, a + b); } else { distributiveProperty(x, a-1, b); assert power(x, a) * power(x, b) == (x * power(x, a-1)) * power(x, b) == x * (power(x, a-1) * power(x, b)) == x * power(x, a - 1 + b) == power(x, a + b); } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(b: real, n: nat) returns (p : real) ensures p == power(b, n) { if n == 0 { return 1.0; } else if n % 2 == 0 { distributiveProperty(b, n/2, n/2); var r := powerOpt(b, n/2); return r * r; } else { distributiveProperty(b, (n-1)/2, (n-1)/2); var r := powerOpt(b, (n-1)/2); return r * r * b; } } // A simple test case to make sure the specification is adequate. method testPower() { var p1 := powerIter(2.0, 5); var p2 := powerOpt(2.0, 5); print "P1: ", p1, "\n"; print "P2: ", p2, "\n"; assert p1 == 32.0; assert p2 == 32.0; }
MFS_tmp_tmpmmnu354t_Praticas_TP9_Power.dfy
249
249
Dafny program: 249
method leq(a: array<int>, b: array<int>) returns (result: bool) ensures result <==> (a.Length <= b.Length && a[..] == b[..a.Length]) || (exists k :: 0 <= k < a.Length && k < b.Length && a[..k] == b[..k] && a[k] < b[k]) { var i := 0; while i < a.Length && i < b.Length { if a[i] < b[i] { return true; } else if a[i] > b[i] { return false; } else {i := i + 1; } } return a.Length <= b.Length; } method testLeq() { var b := new int[][1, 2]; var a1 := new int[][]; var r1 := leq(a1, b); assert r1; var a2 := new int[][1]; var r2 := leq(a2, b); assert r2; var a3 := new int[][1, 2]; var r3 := leq(a3, b); assert r3; var a4 := new int[][1, 1, 2]; var r4 := leq(a4, b); assert a4[1]<b[1] && r4; var a5 := new int[][1, 2, 3]; var r5 := leq(a5, b); assert !r5; var a6 := new int[][2]; var r6 := leq(a6, b); assert !r6; }
method leq(a: array<int>, b: array<int>) returns (result: bool) ensures result <==> (a.Length <= b.Length && a[..] == b[..a.Length]) || (exists k :: 0 <= k < a.Length && k < b.Length && a[..k] == b[..k] && a[k] < b[k]) { var i := 0; while i < a.Length && i < b.Length decreases a.Length - i invariant 0 <= i <= a.Length && 0 <= i <= b.Length invariant a[..i] == b[..i] { if a[i] < b[i] { return true; } else if a[i] > b[i] { return false; } else {i := i + 1; } } return a.Length <= b.Length; } method testLeq() { var b := new int[][1, 2]; var a1 := new int[][]; var r1 := leq(a1, b); assert r1; var a2 := new int[][1]; var r2 := leq(a2, b); assert r2; var a3 := new int[][1, 2]; var r3 := leq(a3, b); assert r3; var a4 := new int[][1, 1, 2]; var r4 := leq(a4, b); assert a4[1]<b[1] && r4; var a5 := new int[][1, 2, 3]; var r5 := leq(a5, b); assert !r5; var a6 := new int[][2]; var r6 := leq(a6, b); assert !r6; }
MFS_tmp_tmpmmnu354t_Testes anteriores_T2_ex5_2020_2.dfy
250
250
Dafny program: 250
// Checks if array 'a' is sorted. predicate isSorted(a: array<int>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Finds a value 'x' in a sorted array 'a', and returns its index, // or -1 if not found. method binarySearch(a: array<int>, x: int) returns (index: int) requires isSorted(a) ensures -1 <= index < a.Length ensures if index != -1 then a[index] == x else x !in a[..] //forall i :: 0 <= i < a.Length ==> a[i] != x { var low, high := 0, a.Length; while low < high x !in a[..low] && x !in a[high..] { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return -1; } // Simple test cases to check the post-condition. method testBinarySearch() { var a := new int[] [1, 4, 4, 6, 8]; var id1 := binarySearch(a, 6); var id2 := binarySearch(a, 3); var id3 := binarySearch(a, 4); } /* a) Identify adequate pre and post-conditions for this method, and encode them as “requires” and “ensures” clauses in Dafny. You can use the predicate below if needed. b) Identify an adequate loop variant and loop invariant, and encode them as “decreases” and “invariant” clauses in Dafny. */
// Checks if array 'a' is sorted. predicate isSorted(a: array<int>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Finds a value 'x' in a sorted array 'a', and returns its index, // or -1 if not found. method binarySearch(a: array<int>, x: int) returns (index: int) requires isSorted(a) ensures -1 <= index < a.Length ensures if index != -1 then a[index] == x else x !in a[..] //forall i :: 0 <= i < a.Length ==> a[i] != x { var low, high := 0, a.Length; while low < high decreases high - low invariant 0 <= low <= high <= a.Length && x !in a[..low] && x !in a[high..] { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return -1; } // Simple test cases to check the post-condition. method testBinarySearch() { var a := new int[] [1, 4, 4, 6, 8]; assert a[..] == [1, 4, 4, 6, 8]; var id1 := binarySearch(a, 6); assert a[3] == 6; // added assert id1 == 3; var id2 := binarySearch(a, 3); assert id2 == -1; var id3 := binarySearch(a, 4); assert a[1] == 4 && a[2] == 4; // added assert id3 in {1, 2}; } /* a) Identify adequate pre and post-conditions for this method, and encode them as “requires” and “ensures” clauses in Dafny. You can use the predicate below if needed. b) Identify an adequate loop variant and loop invariant, and encode them as “decreases” and “invariant” clauses in Dafny. */
MIEIC_mfes_tmp_tmpq3ho7nve_TP3_binary_search.dfy
251
251
Dafny program: 251
function F(n: nat): nat { if n <= 2 then n else F(n-1) + F(n-3)} method calcF(n: nat) returns (res: nat) ensures res == F(n) { var a, b, c := 0, 1, 2; var i := 0; while i < n { a, b, c := b, c, a + c; i := i + 1; } res := a; }
function F(n: nat): nat { if n <= 2 then n else F(n-1) + F(n-3)} method calcF(n: nat) returns (res: nat) ensures res == F(n) { var a, b, c := 0, 1, 2; var i := 0; while i < n decreases n-i invariant 0 <= i <= n invariant a == F(i) && b == F(i+1) && c == F(i+2) { a, b, c := b, c, a + c; i := i + 1; } res := a; }
MIEIC_mfes_tmp_tmpq3ho7nve_exams_appeal_20_p4.dfy
252
252
Dafny program: 252
function R(n: nat): nat { if n == 0 then 0 else if R(n-1) > n then R(n-1) - n else R(n-1) + n } method calcR(n: nat) returns (r: nat) ensures r == R(n) { r := 0; var i := 0; while i < n { i := i + 1; if r > i { r := r - i; } else { r := r + i; } } }
function R(n: nat): nat { if n == 0 then 0 else if R(n-1) > n then R(n-1) - n else R(n-1) + n } method calcR(n: nat) returns (r: nat) ensures r == R(n) { r := 0; var i := 0; while i < n decreases n-i invariant 0 <= i <= n invariant r == R(i) { i := i + 1; if r > i { r := r - i; } else { r := r + i; } } }
MIEIC_mfes_tmp_tmpq3ho7nve_exams_mt2_19_p4.dfy
253
253
Dafny program: 253
type T = int // example // Partitions a nonempty array 'a', by reordering the elements in the array, // so that elements smaller than a chosen pivot are placed to the left of the // pivot, and values greater or equal than the pivot are placed to the right of // the pivot. Returns the pivot position. method partition(a: array<T>) returns(pivotPos: int) requires a.Length > 0 ensures 0 <= pivotPos < a.Length ensures forall i :: 0 <= i < pivotPos ==> a[i] < a[pivotPos] ensures forall i :: pivotPos < i < a.Length ==> a[i] >= a[pivotPos] ensures multiset(a[..]) == multiset(old(a[..])) modifies a { pivotPos := a.Length - 1; // chooses pivot at end of array var i := 0; // index that separates values smaller than pivot (0 to i-1), // and values greater or equal than pivot (i to j-1) var j := 0; // index to scan the array // Scan the array and move elements as needed while j < a.Length-1 { if a[j] < a[pivotPos] { a[i], a[j] := a[j], a[i]; i := i + 1; } j := j+1; } // Swap pivot to the 'mid' of the array a[a.Length-1], a[i] := a[i], a[a.Length-1]; pivotPos := i; }
type T = int // example // Partitions a nonempty array 'a', by reordering the elements in the array, // so that elements smaller than a chosen pivot are placed to the left of the // pivot, and values greater or equal than the pivot are placed to the right of // the pivot. Returns the pivot position. method partition(a: array<T>) returns(pivotPos: int) requires a.Length > 0 ensures 0 <= pivotPos < a.Length ensures forall i :: 0 <= i < pivotPos ==> a[i] < a[pivotPos] ensures forall i :: pivotPos < i < a.Length ==> a[i] >= a[pivotPos] ensures multiset(a[..]) == multiset(old(a[..])) modifies a { pivotPos := a.Length - 1; // chooses pivot at end of array var i := 0; // index that separates values smaller than pivot (0 to i-1), // and values greater or equal than pivot (i to j-1) var j := 0; // index to scan the array // Scan the array and move elements as needed while j < a.Length-1 decreases a.Length-1-j invariant 0 <= i <= j < a.Length invariant forall k :: 0 <= k < i ==> a[k] < a[pivotPos] invariant forall k :: i <= k < j ==> a[k] >= a[pivotPos] invariant multiset(a[..]) == multiset(old(a[..])) { if a[j] < a[pivotPos] { a[i], a[j] := a[j], a[i]; i := i + 1; } j := j+1; } // Swap pivot to the 'mid' of the array a[a.Length-1], a[i] := a[i], a[a.Length-1]; pivotPos := i; }
MIEIC_mfes_tmp_tmpq3ho7nve_exams_mt2_19_p5.dfy
254
254
Dafny program: 254
type T = int // for demo purposes, but could be another type predicate sorted(a: array<T>, n: nat) requires n <= a.Length reads a { forall i,j :: 0 <= i < j < n ==> a[i] <= a[j] } // Use binary search to find an appropriate position to insert a value 'x' // in a sorted array 'a', so that it remains sorted. method binarySearch(a: array<T>, x: T) returns (index: int) requires sorted(a, a.Length) ensures sorted(a, a.Length) //ensures a[..] == old(a)[..] ensures 0 <= index <= a.Length //ensures forall i :: 0 <= i < index ==> a[i] <= x //ensures forall i :: index <= i < a.Length ==> a[i] >= x ensures index > 0 ==> a[index-1] <= x ensures index < a.Length ==> a[index] >= x { var low, high := 0, a.Length; while low < high { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return low; } // Simple test cases to check the post-condition method testBinarySearch() { var a := new int[2] [1, 3]; var id0 := binarySearch(a, 0); var id1 := binarySearch(a, 1); var id2 := binarySearch(a, 2); var id3 := binarySearch(a, 3); var id4 := binarySearch(a, 4); }
type T = int // for demo purposes, but could be another type predicate sorted(a: array<T>, n: nat) requires n <= a.Length reads a { forall i,j :: 0 <= i < j < n ==> a[i] <= a[j] } // Use binary search to find an appropriate position to insert a value 'x' // in a sorted array 'a', so that it remains sorted. method binarySearch(a: array<T>, x: T) returns (index: int) requires sorted(a, a.Length) ensures sorted(a, a.Length) //ensures a[..] == old(a)[..] ensures 0 <= index <= a.Length //ensures forall i :: 0 <= i < index ==> a[i] <= x //ensures forall i :: index <= i < a.Length ==> a[i] >= x ensures index > 0 ==> a[index-1] <= x ensures index < a.Length ==> a[index] >= x { var low, high := 0, a.Length; while low < high decreases high-low invariant 0 <= low <= high <= a.Length invariant low > 0 ==> a[low-1] <= x invariant high < a.Length ==> a[high] >= x { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return low; } // Simple test cases to check the post-condition method testBinarySearch() { var a := new int[2] [1, 3]; var id0 := binarySearch(a, 0); assert id0 == 0; var id1 := binarySearch(a, 1); assert id1 in {0, 1}; var id2 := binarySearch(a, 2); assert id2 == 1; var id3 := binarySearch(a, 3); assert id3 in {1, 2}; var id4 := binarySearch(a, 4); assert id4 == 2; }
MIEIC_mfes_tmp_tmpq3ho7nve_exams_special_20_p5.dfy