I am new in Dafny and I try to figure out why this doesn't work. What I want to do is to insert 2 values in my arrays, priorities, respectively values.
I have the following code:
class Queue<V> {
var size: int;
ghost var capacity: int;
var priorities: array<int>;
var values: array<V>;
predicate Valid()
reads this
{
0 <= size <= capacity &&
capacity == priorities.Length &&
capacity == values.Length
}
constructor(aCapacity: int, defaultValue: V)
requires aCapacity >= 0
ensures Valid()
{
size := 0;
values := new V[aCapacity](i => defaultValue);
priorities := new int[aCapacity];
capacity := aCapacity;
}
method insertValues(priority: int, value: V)
modifies this.values, this.priorities, this
requires Valid()
requires 0 <= size < capacity // here is the problem
ensures Valid()
ensures capacity == values.Length && capacity == priorities.Length
{
this.values[size] := value;
this.priorities[size] := priority;
size := size + 1;
}
}
method Main() {
var queue := new Queue<int>(10, 0);
queue.insertValues(1, 10);
queue.insertValues(2, 11);
}
But when I try to tests my method insertValues in Main it says that
call may violate context's modifies clause
A precondition for this call might not hold.
and the precondition is 0 <= size < capacity. Thank you in advance.
The issue is that Dafny analyzes each method in isolation, using only the specifications of the other methods. See the Dafny FAQ for more information.
You need to add more postconditions to guarantee that certain things aren't changed by insertValues, and you need to also add more postconditions to the constructor so that callers know the initial state. Here is a version that verifies:
class Queue<V> {
var size: int;
ghost var capacity: int;
var priorities: array<int>;
var values: array<V>;
predicate Valid()
reads this
{
0 <= size <= capacity &&
capacity == priorities.Length &&
capacity == values.Length
}
constructor(aCapacity: int, defaultValue: V)
requires aCapacity >= 0
ensures Valid()
ensures fresh(priorities) && fresh(values)
ensures size == 0 && capacity == aCapacity
{
size := 0;
values := new V[aCapacity](i => defaultValue);
priorities := new int[aCapacity];
capacity := aCapacity;
}
method insertValues(priority: int, value: V)
modifies this.values, this.priorities, this
requires Valid()
requires 0 <= size < capacity // here is the problem
ensures Valid()
ensures capacity == old(capacity) && size == old(size) + 1 && values == old(values) && priorities == old(priorities)
{
this.values[size] := value;
this.priorities[size] := priority;
size := size + 1;
}
}
method Main() {
var queue := new Queue<int>(10, 0);
queue.insertValues(1, 10);
queue.insertValues(2, 11);
}
Related
I am trying to verify a code that uses simple modulo operation in a while loop to insert the digits of a number into an array.
I recieve a number,
an array with defined size,
and start - an index in the array from which I fit the most significant digit.
i.e if n=123, a = [w,x,y,z], start=0 then I need to create an array [1,2,3] and then fit it into a: [1,2,3,z]
I start by enforcing that the count of number digits (3 in our example) + the starting index do not exceed the bounds of the target array a.
If it doesn't exceed the bounds, I start slicing the number into digits:
var i:nat := (start + nLength - 1);
var n':=n;
while (i>=start && i>0)
decreases i
****invariant *********
{
a[i] := (n' % 10);
i := i - 1;
n' := n' / 10;
}
I am unable to find the right invariant to enfroce the correctness of the loop I made to iterate over the number and split it into digits.
Any suggestions?
Let me help you with a possible invariant. It looks like this invariant holds, but I was not able to prove it. Probably it requires more engineering.
function computeNumber(a: seq<int>, startIncluded: int, endExcluded: int, multiplier: int): int
decreases endExcluded - startIncluded
requires 0 <= startIncluded <= endExcluded <= |a|
requires startIncluded >= endExcluded
{
if startIncluded >= endExcluded then 0
else a[startIncluded]*multiplier + computeNumber(a, startIncluded+1, endExcluded, multiplier/10)
}
...
var endExcluded := start + nLength;
var i:int := endExcluded;
var n':=n;
ghost var tenPower := 1;
ghost var remainder := 0;
while n' > 0 && i > 0
decreases i
invariant n == n' * tenPower + remainder
invariant computeNumber(a[..], i, endExcluded, tenPower) == remainder
{
i := i - 1;
var digit := n' % 10;
a[i] := digit;
n' := n' / 10;
remainder := digit * tenPower + remainder;
tenPower := tenPower * 10;
}
if n' == 0 && i >= 0 {
assert n == remainder;
assert computeNumber(a[..], i, endExcluded, tenPower) == n;
}
So my friend gave me this task where the sum of squares of positive numbers must be calculated using recursion.
Conditions - The input will be a string with space separated numbers
This is what I've come so far but this shows a runtime error.
Here is the full error https://ideone.com/53oOjN
package main
import(
'fmt',
'strings',
'strconv'
)
var n int = 4
var sum_of_squares int = 0
func sumOfSquares(strArray []string, iterate int) int{
number, _ := strconv.Atoi(strArray[iterate])
if number > 0 {
sum_of_squares += number*number
}
if iterate == n {
return 0 // just to end the recursion
}
return sumOfSquares(strArray, iterate+1)
}
func main() {
str := "1 2 3 4"
strArray := strings.Fields(str)
result := sumOfSquares(strArray, 0)
fmt.Println(sum_of_squares, result)
}
The rule of thumb in recursion is termination condition. It should exist and it should exist in the right place.
func sumOfSquares(strArray []string, iterate int) int{
if iterate >= len(strArray) {
return sum_of_squares
}
number, _ := strconv.Atoi(strArray[iterate]) //TODO: handle err here
sum_of_squares += number*number
return sumOfSquares(strArray, iterate+1)
}
Just for you information: canonical recursion should not save it's state into global fields. I would suggest using following function signature.
func sumOfSquares(strArray []string, iterate, currentSum int) int{
//...
return sumOfSquares(strArray, iterate+1, sum_of_squares)
}
So that you don't need to store sum_of_squares somewhere. You will just pass it to next function invocation.
package main
import (
"fmt"
"strconv"
"strings"
)
var n int
func sumOfSquares(strArray []string, iterate int) int {
number, _ := strconv.Atoi(strArray[iterate])
if iterate == n {
return number * number
}
return ((number * number) + sumOfSquares(strArray, iterate+1))
}
func main() {
str := "1 2 3 4"
strArray := strings.Fields(str)
n = len(strArray) - 1
result := sumOfSquares(strArray, 0)
fmt.Println(result)
}
Indexing starts from 0, so decrease the length by one.
As #peterSO have pointed out, if strings contain unusual characters, it doesn't work, I didn't post the right answer for getting input because you seem to be beginner, but you can read the input, like this instead.
var inp []byte
var loc int
inp, _ = ioutil.ReadFile(fileName)
//add \n so that we don't end up running out of bounds,
//if last byte is integer.
inp = append(inp, '\n')
func scanInt() (res int) {
if loc < len(inp) {
for ; inp[loc] < 48 || inp[loc] > 57; loc++ {
}
for ; inp[loc] > 47 && inp[loc] < 58; loc++ {
res = res<<3 + res<<1 + (int(inp[loc]) - 48)
}
}
return
}
This is faster and scans integers only, and skips all other unusual characters.
I like to keep it simple. I have some few if conditions as well, but hope you like it.
func sumOfSquares(numArr []string) int {
i, err := strconv.Atoi(numArr[0])
rest := numArr[1:]
//Error checking
if err != nil {
fmt.Println(err)
os.Exit(1)
return 0
}
square := i * i
// negative & last number
if i < 0 && len(rest) == 0 {
return square
}
// negative & not last number
if i < 0 && len(rest) > 0 {
return sumOfSquares(rest)
}
// last man standing
if i >= 0 && len(rest) == 0 {
return square
}
return square + sumOfSquares(rest)
}
DEMO : https://play.golang.org/p/WWYxKbvzanJ
My code won't run properly I am trying to get it to find peaks including the end and beginning of the array and then compare all the indexes that aren't the beginning or end to the index before and after them does anyone know why I am getting the out of index range error?
package main
import "fmt"
func linearFindPeaks(arg []int) []int {
peaks := []int{}
lenArg := len(arg)
for i := 0; i < lenArg; i++ {
//if its the first element run this
//second if statement for the end of array
// for default statements
if arg[0] > arg[1] {
peaks = append(peaks, arg[0])
} else if arg[lenArg-1] > arg[lenArg-2] {
peaks = append(peaks, arg[lenArg-1])
} else if arg[i] > arg[i+1] && arg[i] > arg[i-1] && arg[i] != arg[0] && arg[i] != arg[lenArg-1] {
peaks = append(peaks, arg[i])
}
}
fmt.Println(peaks)
return peaks
}
func main() {}
Playground: https://play.golang.org/p/2JRgEyRA50
Two possibilities i can see. Firstly, in the first else if:
}else if arg[lenArg - 1] > arg[lenArg -2] {
If lenArg is 1 then lenArg-2will be -1. This means arg[lenArg-2] is arg[-1] which will give you out of bounds.
Secondly, in the second else if:
} else if arg[i] > arg[i+1] ... {
On the last iteration over the loop, i will be lenArg-1, if you add 1 to this you'll get arg[lenArg-1+1] or arg[lenArg] which will out of bounds. (The last available index is at lenArg-1)
The Go Programming Language Specification
Index expressions
A primary expression of the form
a[x]
denotes the element of the slice a indexed by x.
The index x must be of integer type or untyped; it is in range if
0 <= x < len(a)
Otherwise it is out of range.
You need to pay attention to corner cases like lengths 0, 1, and 2 for indices i - 1, i, i + 1 out of range. For example,
package main
// For array a, a[i] is a peak if it is not smaller than its neighbor(s),
// where a[-1] = a[n] = -∞.
func findPeaks(a []int) []int {
var p []int
// special cases
if len(a) == 0 {
return p
}
if len(a) == 1 {
return append(p, a[0])
}
// first
i := 0
if a[i] >= a[i+1] {
p = append(p, a[i])
}
// first < i < last
for i = 1; i < len(a)-1; i++ {
if a[i-1] <= a[i] && a[i] >= a[i+1] {
p = append(p, a[i])
}
}
// last
i = len(a) - 1
if a[i-1] <= a[i] {
p = append(p, a[i])
}
return p
}
func main() {}
Playground: https://play.golang.org/p/9klj1wYnXZ
This is a trivial algorithmic question, I believe, but I don't seem to be able to find an efficient and elegant solution.
We have 3 arrays of int (Aa, Ab, Ac) and 3 cursors (Ca, Cb, Cc) that indicate an index in the corresponding array. I want to identify and increment the cursor pointing to the smallest value. If this cursor is already at the end of the array, I will exclude it and increment the cursor pointing to the second smallest value. If there is only 1 cursor that is not at the end of the array, we increment this one.
The only solutions I can come up are complicated and/or not optimal. For example, I always end up with a huge if...else...
Does anyone see a neat solution to this problem ?
I am programming in C++ but feel free to discuss it in pseudo-code or any language you like.
Thank you
Pseudo-java code:
int[] values = new int[3];
values[0] = aa[ca];
values[1] = ab[cb];
values[2] = ac[cc];
Arrays.sort(values);
boolean done = false;
for (int i = 0; i < 3 && !done; i++) {
if (values[i] == aa[ca] && ca + 1 < aa.length) {
ca++;
done = true;
}
else if (values[i] == ab[cb] && cb + 1 < ab.length) {
cb++;
done = true;
}
else if (cc + 1 < ac.length) {
cc++;
done = true;
}
}
if (!done) {
System.out.println("cannot increment any index");
stop = true;
}
Essentially, it does the following:
initialize an array values with aa[ca], ab[cb] and ac[cc]
sort values
scan values and increment if possible (i.e. not already at the end of the array) the index of the corresponding value
I know, sorting is at best O(n lg n), but I'm only sorting an array of 3 elements.
what about this solution:
if (Ca != arraySize - 1) AND
((Aa[Ca] == min(Aa[Ca], Ab[Cb], Ac[Cc]) OR
(Aa[Ca] == min(Aa[Ca], Ab[Cb]) And Cc == arraySize - 1) OR
(Aa[Ca] == min(Aa[Ca], Ac[Cc]) And Cb == arraySize - 1) OR
(Cc == arraySize - 1 And Cb == arraySize - 1))
{
Ca++;
}
else if (Cb != arraySize - 1) AND
((Ab[Cb] == min(Ab[Cb], Ac[Cc]) OR (Cc == arraySize - 1))
{
Cb++;
}
else if (Cc != arraySize - 1)
{
Cc++;
}
Pseudo code: EDIT : tidied it up a bit
class CursoredArray
{
int index;
std::vector<int> array;
int val()
{
return array[index];
}
bool moveNext()
{
bool ret = true;
if( array.size() > index )
++index;
else
ret = false;
return ret;
}
}
std::vector<CursoredArray> arrays;
std::vector<int> order = { 0, 1, 2 };//have a default order to start with
if( arrays[0].val() > arrays[1].val() )
std::swap( order[0], order [1] );
if( arrays[2].val() < arrays[order[1]].val() )//if the third is less than the largest of the others
{
std::swap( order[1], order [2] );
if( arrays[2].val() < arrays[order[0]].val() )//if the third is less than the smallest of the others
std::swap( order[0], order [1] );
}
//else third pos of order is already correct
bool end = true;
for( i = 0; i < 3; ++i )
{
if( arrays[order[i]].MoveNext() )
{
end = false;
break;
}
}
if( end )//have gone through all the arrays
I was trying to solve Project Euler problem number 7 using scala 2.8
First solution implemented by me takes ~8 seconds
def problem_7:Int = {
var num = 17;
var primes = new ArrayBuffer[Int]();
primes += 2
primes += 3
primes += 5
primes += 7
primes += 11
primes += 13
while (primes.size < 10001){
if (isPrime(num, primes)) primes += num
if (isPrime(num+2, primes)) primes += num+2
num += 6
}
return primes.last;
}
def isPrime(num:Int, primes:ArrayBuffer[Int]):Boolean = {
// if n == 2 return false;
// if n == 3 return false;
var r = Math.sqrt(num)
for (i <- primes){
if(i <= r ){
if (num % i == 0) return false;
}
}
return true;
}
Later I tried the same problem without storing prime numbers in array buffer. This take .118 seconds.
def problem_7_alt:Int = {
var limit = 10001;
var count = 6;
var num:Int = 17;
while(count < limit){
if (isPrime2(num)) count += 1;
if (isPrime2(num+2)) count += 1;
num += 6;
}
return num;
}
def isPrime2(n:Int):Boolean = {
// if n == 2 return false;
// if n == 3 return false;
var r = Math.sqrt(n)
var f = 5;
while (f <= r){
if (n % f == 0) {
return false;
} else if (n % (f+2) == 0) {
return false;
}
f += 6;
}
return true;
}
I tried using various mutable array/list implementations in Scala but was not able to make solution one faster. I do not think that storing Int in a array of size 10001 can make program slow. Is there some better way to use lists/arrays in scala?
The problem here is that ArrayBuffer is parameterized, so what it really stores are references to Object. Any reference to an Int is automatically boxed and unboxed as needed, which makes it very slow. It is incredibly slow with Scala 2.7, which uses a Java primitive to do that, which does it very slowly. Scala 2.8 takes another approach, making it faster. But any boxing/unboxing will slow you down. Furthermore, you are first looking up the ArrayBuffer in the heap, and then looking up again for java.lang.Integer containing the Int -- two memory accesses, which makes it way slower than your other solution.
When Scala collections become specialized, it should be plenty faster. Whether it should be enough to beat your second version or not, I don't know.
Now, what you may do to get around that is to use Array instead. Because Java's Array are not erased, you avoid the boxing/unboxing.
Also, when you use for-comprehensions, your code is effectively stored in a method which is called for each element. So you are also making many method calls, which is another reason this is slower. Alas, someone wrote a plugin for Scala which optimizes at least one case of for-comprehensions to avoid that.
Using Array should make it work in about zero seconds with the right algorithm. This, for example, takes about 7 milliseconds on my system:
class Primes(bufsize: Int) {
var n = 1
val pbuf = new Array[Int](bufsize max 1)
pbuf(0) = 2
def isPrime(num: Int): Boolean = {
var i = 0
while (i < n && pbuf(i)*pbuf(i) <= num) {
if (num % pbuf(i) == 0) return false
i += 1
}
if (pbuf(i)*pbuf(i) < num) {
i = pbuf(i)
while (i*i <= num) {
if (num % i == 0) return false
i += 2
}
}
return true;
}
def fillBuf {
var i = 3
n = 1
while (n < bufsize) {
if (isPrime(i)) { pbuf(n) = i; n += 1 }
i += 2
}
}
def lastPrime = { if (n<bufsize) fillBuf ; pbuf(pbuf.length-1) }
}
object Primes {
def timedGet(num: Int) = {
val t0 = System.nanoTime
val p = (new Primes(num)).lastPrime
val t1 = System.nanoTime
(p , (t1-t0)*1e-9)
}
}
Result (on second call; first has some overhead):
scala> Primes.timedGet(10001)
res1: (Int, Double) = (104743,0.00683394)
I think you have to think out of the box :)
Because the problem is manageable, you can use Sieve of Eratosthenes to solve it very efficiently.
Here's a recursive solution (using the isPrime function from your first solution). It seems to be good Scala style to prefer immutability (i.e. to try not to use vars) so I've done that here (in fact there are no vars or vals!). I don't have a Scala installation here though so can't tell if this is actually any quicker!
def problem_7:Int = {
def isPrime_(n: Int) = (n % 6 == 1 || n % 6 == 5) && isPrime(n)
def process(n: Int, acc: List[Int]): Int = {
if (acc.size == 10001) acc.head
else process(n+1, if isPrime_(n) n :: acc else acc)
}
process(1, Nil)
}