This is the code for Bulls and Cows game, simply it just we have 2 array a[] and b[] with the same length, if a[i] == b[i] then Bulls += 1, if a[i] in b && a[i] != b[i] then Cows += 1.
I have written the Bulls and Cows function, but the method BullCows have some problem when calculate it, it make my assert fail.
`
function bullspec(s:seq<nat>, u:seq<nat>): nat
requires |s| > 0
requires |u| > 0
requires |s| == |u|
{
var index:=0;
if |s| == 1 then (
if s[0]==u[0]
then 1 else 0
) else (
if s[index] != u[index]
then bullspec(s[index+1..],u[index+1..])
else 1+bullspec(s[index+1..],u[index+1..])
)
}
function cowspec(s:seq<nat>, u:seq<nat>): nat
requires |s| > 0
requires |u| > 0
requires |s| <= |u|
{
var extra:= |u|-|s|;
var index:=0;
if |s| == 1 then (
if s[0] in u
then 1 else 0
) else(
if s[index] in u && s[index]!=u[extra]
then (1+ cowspec(s[index+1..],u))
else cowspec(s[index+1..],u)
)
}
method BullsCows (s:seq<nat>, u:seq<nat>) returns (b:nat, c:nat)
requires |s|>0 && |u|>0 &&|s|==|u|
// No duplicates in array
requires forall i, j | 0 <= i < |s| && 0 <= j < |s| && i != j :: s[i] != s[j]
requires forall i, j | 0 <= i < |u| && 0 <= j < |u| && i != j :: u[i] != u[j]
ensures forall k :: 0 <= k < |s| && s[k] !in u ==> b == c == 0
ensures forall k :: 0 <= k < |s| && s[k] in u ==> (c + b) > 0
{
var index := 0;
b := 0;
c := 0;
while(index<|s|)
invariant index <= |s|
invariant forall k :: 0 <= k < index && s[k] in u ==> (b + c) > 0
{
if s[index] in u {
if s[index] == u[index]{
b:=b+1;
} else {
c:=c+1;
}
}
index:=index + 1;
}
}
method NotMain()
{
var sys:seq<nat> := [4,2,9,3,1];
var usr:seq<nat> := [1,2,3,4,5];
assert bullspec(sys, usr) == 1; //True
assert cowspec(sys, usr) == 3; //True
var b:nat, c:nat := BullsCows(sys, usr);
assert b == 1; //Not true
assert c == 3; //Not true
}
`
The method NotMain said that assert b == 1; and assert c==3; are not true, this is Dafny language, please could someone help me with this logical, I'm banging my head.
I try put on many ensures in the BullsCows method but there's nothing happen
The problem is that the postcondition on BullsCows() is not strong enough to prove the final two assertions. In particular, there is no connection between the operation of BullsCows() and the specifications bullspec() and cowspec(). You need to connect these things together.
To illustrate I'm going to use a simpler example which is easier to follow. As for your example above, the final assertion fails in the following:
function sumspec(xs: seq<nat>, i: nat) : nat
requires i <= |xs| {
if |xs| == 0 || i == 0 then 0
else sumspec(xs,i-1) + xs[i-1]
}
method sum(s:seq<nat>) returns (r:nat) {
r := 0;
for i := 0 to |s| {
r := r + s[i];
}
return r;
}
method main() {
assert sumspec([1,2,3],3) == 6;
var r := sum([1,2,3]);
assert r == 6;
}
Whilst sumspec() is a valid specification for sum() we have not connected these two things. As such, Dafny assumes that sum() can return any value for r!
To connect the specification (sumspec) with its implementation (sum) we need a stronger postcondition:
method sum(s:seq<nat>) returns (r:nat)
ensures r == sumspec(s,|s|) {
r := 0;
for i := 0 to |s|
invariant r == sumspec(s,i) {
r := r + s[i];
}
return r;
}
Here, r == sumspec(s,|s|) connects the specification with the result of our implementation. We also added a loop invariant to help Dafny show this postcondition holds.
Related
I study verification at the university using promela. And as an example, i need to solve algorithmic puzzle about frogs. I tried to solve the problem but something doesn't work right
In how many moves will the frogs exchange places? Frogs jump in turn on an empty cage when it is nearby or through one frog of the opposite color.
enter image description here
bool all_frog_done;
active proctype frog_jump()
{
byte i = 0;
byte position[7];
position[0] = 1;
position[1] = 1;
position[2] = 1;
position[3] = 0;
position[4] = 2;
position[5] = 2;
position[6] = 2;
all_frog_done = false;
printf("MSC: position[0] %d position[1] %d position[2] %d position[3] %d position[4] %d position[5] %d position[6] %d \n", position[0], position[1], position[2], position[3], position[4], position[5], position[6]);
do
:: (position[0] == 2) && (position[1] == 2) && (position[2] == 2) && (position[3] == 0) && (position[4] == 1) && (position[5] == 1) && (position[6] == 1) ->
all_frog_done = true; break;
:: else ->
if
:: (position[i] == 1) && (position[i+1] == 0) && (i != 6) ->
position[i] = 0;
position[i+1] = 1;
:: (position[i] == 2) && (position[i-1] == 0) && (i != 0) ->
position[i] = 0;
position[i-1] = 2;
:: (position[i] == 1) && (position[i+1] == 2) && (position[i+2] == 0) && (i <= 4)->
position[i] = 0;
position[i+2] = 1;
:: (position[i] == 2) && (position[i-1] == 1) && (position[i-2] == 0) && (i >= 2)->
position[i] = 0;
position[i-2] = 2;
fi;
printf("MSC: position[0] %d position[1] %d position[2] %d position[3] %d position[4] %d position[5] %d position[6] %d \n", position[0], position[1], position[2], position[3], position[4], position[5], position[6]);
if
:: (i < 7) -> i++;
:: (i > 0) -> i--;
fi;
od;
}
I've come across a programming question at reddit (Take a look at the link for the question)
This was one the solutions in Python:
s="112213"
k=2
result=0
for i in range(len(s)):
num_seen = 0
window = {}
for ind in range(i, len(s)):
if not s[ind] in window:
num_seen += 1
window[s[ind]] = 1
else:
window[s[ind]] += 1
if window[s[ind]] == k:
num_seen -= 1
if num_seen == 0:
result +=1
elif window[s[ind]] > k:
break
print(result)
I've tried to port this solution into Raku and here is my code:
my #s=<1 1 2 2 1 3>;
my $k=2;
my $res=0;
for ^#s {
my $seen = 0;
my %window;
for #s[$_..*] {
if $^a == %window.keys.none {
$seen++;
%window{$^a} = 1;}
else {
%window{$^a} += 1;}
if %window{$^a} == $k {
$seen--;
if $seen == 0 {
$res++;} }
elsif %window{$^a} > $k {
last;}}}
say $res;
It gives this error:
Use of an uninitialized value of type Any in a numeric context in a block at ... line 13
How to fix it?
I don't feel that's a MRE. There are too many issues with it for me to get in to. What I did instead is start from the original Python and translated that. I'll add some comments:
my \s="112213" .comb; # .comb to simulate Python string[n] indexing.
my \k=2;
my $result=0; # result is mutated so give it a sigil
for ^s -> \i { # don't use $^foo vars with for loops
my $num_seen = 0;
my \window = {}
for i..s-1 -> \ind {
if s[ind] == window.keys.none { # usefully indent code!
$num_seen += 1;
window{s[ind]} = 1
} else {
window{s[ind]} += 1
}
if window{s[ind]} == k {
$num_seen -= 1;
if $num_seen == 0 {
$result +=1
}
} elsif window{s[ind]} > k {
last
}
}
}
print($result)
displays 4.
I'm not saying that's a good solution in Raku. It's just a relatively mechanical translation. Hopefully it's helpful.
As usual, the answer by #raiph is correct. I just want to do the minimal changes to your program that get it right. In this case, it's simply adding indices to both loops to make stuff clearer. You were using the context variable $_ in the first, and $^a in the second (inner), and it was getting unnecesarily confusing.
my #s=<1 1 2 2 1 3>;
my $k=2;
my $res=0;
for ^#s -> $i {
my $seen = 0;
my %window;
for #s[$i..*] -> $c {
if $c == %window.keys.none {
$seen++;
%window{$c} = 1;
} else {
%window{$c} += 1;
}
if %window{$c} == $k {
$seen--;
if $seen == 0 {
$res++;
}
} elsif %window{$c} > $k {
last;
}
}
}
say $res;
As you see , besides trying to indent everything a bit more properly, the only additional thing is to add -> $i and -> $c so that loops are indexed, and then use them where you were using implicit variables.
How to change 12345 to 54321?
With a string, you can change the string to a rune, and reverse it, but you cannot do the same for an integer. I have searched and found no one talking about this. Examples
131415 >>> 514131
1357 >>> 7531
123a >>> ERROR
-EDIT-
I was thinking, why not create a slice and index that?
Then I realized that you can't index int
(http://play.golang.org/p/SUSg04tZsc)
MY NEW QUESTION IS
How do you index an int?
OR
How do you reverse a int?
Here is a solution that does not use indexing an int
package main
import (
"fmt"
)
func reverse_int(n int) int {
new_int := 0
for n > 0 {
remainder := n % 10
new_int *= 10
new_int += remainder
n /= 10
}
return new_int
}
func main() {
fmt.Println(reverse_int(123456))
fmt.Println(reverse_int(100))
fmt.Println(reverse_int(1001))
fmt.Println(reverse_int(131415))
fmt.Println(reverse_int(1357))
}
Result:
654321
1
1001
514131
7531
Go playground
I converted the integer to a string, reverse the string, and convert the result back to a string.
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(reverse_int(123456))
fmt.Println(reverse_int(100))
fmt.Println(reverse_int(1001))
fmt.Println(reverse_int(131415))
fmt.Println(reverse_int(1357))
}
func reverse_int(value int) int {
intString := strconv.Itoa(value)
newString := ""
for x := len(intString); x > 0; x-- {
newString += string(intString[x - 1])
}
newInt, err := strconv.Atoi(newString)
if(err != nil){
fmt.Println("Error converting string to int")
}
return newInt
}
Very similar to the first answer but this checks to make sure you don't go out of bounds on the type.
func reverse(x int) int {
rev := 0
for x != 0 {
pop := x % 10
x /= 10
if rev > math.MaxInt32/10 || (rev == math.MaxInt32 /10 && pop > 7) {
return 0
}
if rev < math.MinInt32/10 || (rev == math.MinInt32/10 && pop < -8) {
return 0
}
rev = rev * 10 + pop
}
return rev
}
Also flips negative numbers int
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}
func reverse_int(n int) int {
newInt := 0
sign := 1
if n < 0 {
sign = -1
}
n = Abs(n)
for n > 0 {
remainder := n % 10
newInt = newInt*10 + remainder
n /= 10
}
return newInt * sign
}
func main() {
fmt.Println(reverse_int(-100))
fmt.Println(reverse_int(-1001))
fmt.Println(reverse_int(131415))
fmt.Println(reverse_int(1357))
}
Similar to Fokiruna's answer but also checks for a 32bit overflow
func reverse(x int) int {
result, sign := 0, 1
if(x < 0) {
sign = -1
x = -x
}
for x > 0 {
remainder := x % 10;
result = result * 10 + remainder
x = x/10
}
var checkInt int = int(int32(result))
if checkInt != result {
return 0
}
return result * sign
}
I have the following zaMap (see full code here: http://rise4fun.com/Dafny/LCaM):
class zaMap {
var busybits :array<bool>;
var keys : array<int>;
var values : array<int>;
predicate wellformed ()
reads busybits, keys, values, this
{
busybits != null && keys != null && values != null &&
keys != values &&
busybits.Length == keys.Length &&
keys.Length == values.Length
}
// ... more predicates and methods follow
method put(k : int, v : int) returns (success : bool)
requires wellformed()
modifies busybits, keys, values
ensures !success ==> full()
ensures success ==> mapsto(k, v)
{
var i := findEmpty();
if (i < 0)
{
success := false;
return;
}
assert !busybits[i];
busybits[i] := true;
keys[i] := k;
values[i] := v;
success := true;
}
//...
Now I want to add more specifications to the put method. For example, I want to ensure, that if the return value is success == true, then a map was !full() before the function call, or equivalently if a map not full(), it is guaranteed to put there.
The problem is that, in the precondition "requires" I don't know yet what it will return, and in the postcondition "ensures" I don't have an original map anymore. What people do about that?
You can use the old keyword. Let's take a look at an example. The following method sets to zero all positions of an array containing the element x and leaving the rest as they are. Here's the code:
method setToZero(a: array<int>, x : int )
requires a != null;
modifies a;
ensures forall i :: 0 <= i < a.Length && old(a[i]) == x ==> a[i] == 0;
ensures forall i :: 0 <= i < a.Length && old(a[i]) != x ==> a[i] == old(a[i]);
{
var j := 0;
while (j < a.Length)
invariant 0 <= j <= a.Length;
invariant forall i :: 0 <= i < j && old(a[i]) == x ==> a[i] == 0;
invariant forall i :: 0 <= i < j && old(a[i]) != x ==> a[i] == old(a[i]);
invariant forall i :: j <= i < a.Length ==> a[i] == old(a[i]);
{
if (a[j] == x) {
a[j] := 0;
}
j := j + 1;
}
}
is there any existing linq function or similiar functions to detect how often values in an ordered list changes from less than zero to greater than zero?
As example, values:
5
2
-2
-5
8 <--- First
6
2
0
1
-3
-5
-3
2 <--- Second
Total count: 2
Sure - it's certainly easy if you're using .NET 4 or higher, using Zip:
// TODO: Consider how you want to handle 0 itself
var count = list.Zip(list.Skip(1), (x, y) => new { x, y })
.Count(pair => pair.x > 0 && pair.y < 0);
That shouldn't be hard to convert into VB if you know VB well :)
Alternatively, if you've really got a list, you can just do it "manually" pretty easily without LINQ:
int count = 0;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > 0 && list[i + 1] < 0)
{
count++;
}
}
You can implement this in one pass using Aggregate:
seq.Aggregate(new { Count=0, LastN = 0}, (state, n) => new {
Count = state.Count + (n > 0 && state.LastN < 0 ? 1 : 0),
LastN = n == 0 ? state.LastN : n
}).Count
This takes into account your wish to include "gradual" transitions such as -1,0,1.
However, a foreach may be easier, simply because it's more conventional. It'll also be faster:
var count = 0;
var lastN = 0;
foreach(var n in seq) {
if(n > 0 && lastN < 0)
count++;
if (n != 0)
lastN = n;
}