How do I iterate over the elements of a finite set object in Dafny? - iterator

What is the best way to iterate over the elements of a finite set object in Dafny? An example of working code would be delightful.

This answer explains how to do it using a while loop, rather than by defining an iterator. The trick is to use the "assign such that" operator,
:|, to obtain a value y such that that y is in the set, and then repeat on that set with the y removing, continuing until there are not more elements. The decreases clause is necessary here. With it, Dafny proves termination of the while loop, but without it, not.
method Main()
{
var x: set<int> := {1, 2, 3};
var c := x;
while ( c != {} )
decreases c;
{
var y :| y in c;
print y, ", ";
c := c - { y };
}
}

Related

Invariant for Hoare-Logic on RandomSearch

I'm trying to proof the following RandomSeach-Algorithm and to figure out the invariant for the loop.
Since the function randomIndex(..) creates a random number I cannot use an invariant like
𝑠 ≥ 0 ∧ 𝑠 < 𝑖 − 1 ⇒ 𝑓[𝑠] ≠ 𝑣𝑎𝑙𝑢e
. That means, all elements between 0 and i-1, with i is the index of the current checked element, is not the searched element.
So I thought I define a hypothetical sequence r, that contains all elements that have already been compared to the searched value or are going to be compared to the searched value. Thats why it is just a hypothetical sequence, because I actually do not know the elements that are going to be compared to the searched value until they have been realy compared.
That means it applies r.lenght() ≤ runs and in the case the searched element was found
(r[r.lenght()-1] = value) ↔ (r[currentRun] = value).
Then I can define a invariant like:
𝑠 ≥ 0 ∧ 𝑠 < currentRun ⇒ r[𝑠] ≠ 𝑣𝑎𝑙𝑢e
Can I do this, because the sequence r is not real? It does not feel right. Does anyone have a diffrent idea for an invariant?
The program:
public boolean RandomSearch (int value, int[] f, int runs) {
int currentRun = 0;
boolean found = false;
while (currentRun < runs || !found) {
int x = randomIndex(0, n-1)
if (value == f[x]) {
found = true;
}
currentRun = currentRun + 1;
}//end while
return found;
}//end RandomSearch
Ok,
I use following invariant
currentRun <= runs & f.length > 0
Than I can proof the algorithm :)

Why does `variable++` increment the variable but `variable + 1` does not?

Here's the problem in which I encountered this issue:
The function should compare the value at each index position and score a point if the value for that position is higher. No point if they are the same. Given a = [1, 1, 1] b = [1, 0, 0] output should be [2, 0]
fun compareArrays(a: Array<Int>, b: Array<Int>): Array<Int> {
var aRetVal:Int = 0
var bRetVal:Int = 0
for(i in 0..2){
when {
a[i] > b[i] -> aRetVal + 1 // This does not add 1 to the variable
b[i] > a[i] -> bRetVal++ // This does...
}
}
return arrayOf(aRetVal, bRetVal)
}
The IDE even says that aRetVal is unmodified and should be declared as a val
What others said is true, but in Kotlin there's more. ++ is just syntactic sugar and under the hood it will call inc() on that variable. The same applies to --, which causes dec() to be invoked (see documentation). In other words a++ is equivalent to a.inc() (for Int or other primitive types that gets optimised by the compiler and increment happens without any method call) followed by a reassignment of a to the incremented value.
As a bonus, consider the following code:
fun main() {
var i = 0
val x = when {
i < 5 -> i++
else -> -1
}
println(x) // prints 0
println(i) // prints 1
val y = when {
i < 5 -> ++i
else -> -1
}
println(y) // prints 2
println(i) // prints 2
}
The explanation for that comes from the documentation I linked above:
The compiler performs the following steps for resolution of an operator in the postfix form, e.g. a++:
Store the initial value of a to a temporary storage a0;
Assign the result of a.inc() to a;
Return a0 as a result of the expression.
...
For the prefix forms ++a and --a resolution works the same way, and the effect is:
Assign the result of a.inc() to a;
Return the new value of a as a result of the expression.
Because
variable++ is shortcut for variable = variable + 1 (i.e. with assignment)
and
variable + 1 is "shortcut" for variable + 1 (i.e. without assignment, and actually not a shortcut at all).
That is because what notation a++ does is actually a=a+1, not just a+1. As you can see, a+1 will return a value that is bigger by one than a, but not overwrite a itself.
Hope this helps. Cheers!
The equivalent to a++ is a = a + 1, you have to do a reassignment which the inc operator does as well.
This is not related to Kotlin but a thing you'll find in pretty much any other language

Using an iterator, how do I skip a number of values and then display the rest?

Random access to the elements is not allowed.
let vec = vec![1,2,3,4,5,6,7,8,9,0];
let n = 3;
for v in vec.iter().rev().take(n) {
println!("{}", v);
}
// this printed: 0, 9, 8
// need: 8, 9, 0
for v in vec.iter().rev().skip(n).rev() does not work.
I think the code you wrote does what you're asking it to.
You are reversing the vec with rev() and then you're taking the first 3 elements of the reversed vector (therefore 0, 9, 8)
To obtain the last 3 in non-reversed order you can skip to the end of the vector minus 3 elements, without reversing it:
let vec = vec![1,2,3,4,5,6,7,8,9,0];
let n = vec.len() - 3;
for v in vec.iter().skip(n) {
println!("{}", v);
}
Neither skip nor take yield DoubleEndIterator, you have to either:
skip, which is O(N) in the number of skipped items
collect the result of .rev().take(), and then rev it, which is O(N) in the number of items to be printed, and requires allocating memory for them
The skip is obvious, so let me illustrate the collect:
let vec = vec![1,2,3,4,5,6,7,8,9,0];
let vec: Vec<_> = vec.iter().rev().take(3).collect();
for v in vec.iter().rev() {
println!("{}", v);
}
Of course, the inefficiency is due to you shooting yourself in the foot by avoiding random access in the first place...
Based on the comments, I guess you want to iterate specifically through the elements of a Vec or slice. If that is the case, you could use range slicing, as shown below:
let vec = vec![1,2,3,4,5,6,7,8,9,0];
let n = vec.len() - 3;
for v in &vec[n..] {
println!("{}", v);
}
The big advantage of this approach is that it doesn't require to skip through elements you are not interested in (which may have a big cost if not optimized away). It will just make a new slice and then iterate through it. In other words, you have the guarantee that it will be fast.

Palindrome of a number - No console log

So I tried to write a code that finds the largest palindromic number from two (3 spaces long) multiplied numbers. Does my code work fine or are there no palindromes for this?
function checkPalindrom(str) {
return str === str.split('').reverse().join('');
}; //Declares the funciton to check if a string is a palindrome
var x = 999;
var y = 999;
var z = 0;
var n = z.toString(); //Declares that n is the string of z
for (i=0; i<899; i++) { //For loop: counts from 0 to 899
x*y===z; //Is this correct? z is set equal to x*y
if(checkPalindrom(n) === true) { //If n is a palindrome,
console.log(n); //Write out the palindrome
} else {
x-=1; //subtract 1 from x and run again
}
};
Also, what is the best way to check for all combinations of 3 digit numbers? Because right now I am just checking for any number from 100 to 999, but I actually need to check for all combinations...
Your post has a few problems, as well as multiple questions in it. I'll try to hone in on the major stuff but, as this is a fairly standard type of Programming 101 homework question, I'm not going to give you an exact answer right out.
First off, there are three different 'equals' in javascript, =, ==, and ===. A single = is an assignment operator and it always works from right to left. Thus,
var x = 2;
assigns the value of 2 to the variable x. In your code,
x*y === z;
has a couple of problems. First off, it is backwards. Secondly, it uses === but should be using =.
z = x*y;
That is what you were trying to put here.
In javascript, == and === are both comparitives. The triple === adds type comparison and is stronger but generally unnecessary. In almost all cases, == is sufficient. But, what it does is compare the values like inside an if statement:
if(x == 2)
This just checks if the value of x is equal to the value of 2, but the values themselves do not change.
Ok, for your other question: "number from 100 to 999, but I actually need to check for all combinations..."
The best way to handle this is a double loop:
var z;
for(var x = 100; x < 1000; x++)
for(var y = x; y < 1000; y++)
z = x*y;
This will first let x = 100, then check 100 * every number from 100 to 999. Then you let x = 101 and check 101* every number from 101 to 999.
function checkPalindrom(str) {
return str === str.split('').reverse().join('');
}; //Declares the funciton to check if a string is a palindrome
var x;
var y;
var z;
var n;
var max = 0;
for (x=999; x >= 100; x--) {
for (y=999; y >= 100; y--) {
z = x*y;
n = z.toString();
if(checkPalindrom(n) === true && max < z) {
console.log(n);
max = z;
}
}
}

game maker random cave generation

I want to make a cave explorer game in game maker 8.0.
I've made a block object and an generator But I'm stuck. Here is my code for the generator
var r;
r = random_range(0, 1);
repeat(room_width/16) {
repeat(room_height/16) {
if (r == 1) {
instance_create(x, y, obj_block)
}
y += 16;
}
x += 16;
}
now i always get a blank frame
You need to use irandom(1) so you get an integer. You also should put it inside the loop so it generates a new value each time.
In the second statement, you are generating a random real value and storing it in r. What you actually require is choosing one of the two values. I recommend that you use the function choose(...) for this. Here goes the corrected statement:
r = choose(0,1); //Choose either 0 or 1 and store it in r
Also, move the above statement to the inner loop. (Because you want to decide whether you want to place a block at the said (x,y) location at every spot, right?)
Also, I recommend that you substitute sprite_width and sprite_height instead of using the value 16 directly, so that any changes you make to the sprite will adjust the resulting layout of the blocks accordingly.
Here is the code with corrections:
var r;
repeat(room_width/sprite_width) {
repeat(room_height/sprite_height) {
r = choose(0, 1);
if (r == 1)
instance_create(x, y, obj_block);
y += sprite_height;
}
x += sprite_width;
}
That should work. I hope that helps!
Looks like you are only creating a instance if r==1. Shouldn't you create a instance every time?
Variable assignment r = random_range(0, 1); is outside the loop. Therefore performed only once before starting the loop.
random_range(0, 1) returns a random real number between 0 and 1 (not integer!). But you have if (r == 1) - the probability of getting 1 is a very small.
as example:
repeat(room_width/16) {
repeat(room_height/16) {
if (irandom(1)) {
instance_create(x, y, obj_block)
}
y += 16;
}
x += 16;
}
Here's a possible, maybe even better solution:
length = room_width/16;
height = room_height/16;
for(xx = 0; xx < length; xx+=1)
{
for(yy = 0; yy < height; yy+=1)
{
if choose(0, 1) = 1 {
instance_create(xx*16, yy*16, obj_block); }
}
}
if you want random caves, you should probably delete random sections of those blocks,
not just single ones.
For bonus points, you could use a seed value for the random cave generation. You can also have a pathway random generation that will have a guaranteed path to the finish with random openings and fake paths that generate randomly from that path. Then you can fill in the extra spaces with other random pieces.
But in regards to your code, you must redefine the random number each time you are placing a block, which is why all of them are the same. It should be called inside of the loops, and should be an integer instead of a decimal value.
Problem is on the first line, you need to put r = something in the for cycle