What is the most elegant way to do the next stuff:
int i = oneOrZero;
if (i == 0) {
i = 1;
} else {
i = 0;
}
You can assume that i can have only 1 or 0 value.
i ^= 1;
XOR the value with 1. This gives you both ways (in case you need to flip 0 <--> 1 either way):
0 ^ 1 = 1
1 ^ 1 = 0
subtraction?
i = 1 - i;
i = (i == 0)?1:0 is one way, though I like #Jimmy's and #Yuval's versions better.
i = ( i + 1 ) % 2, though I think we all agree the subtraction or xor method is better! (Though it has the added benefit of "flipping the switch" for more than binary.)
Use Bitwise XOR operator:
i ^= 1;
int x = 0;
x=(int)Math.cos(x);
System.out.println("X value "+x);
Related
I have the following code:
public static void main(String[] args) {
int a = 3;
int b = 7;
int x = b; // x=b
int res = a; // res = a
int y = 1;
int invariant = 0;
System.out.println("a|b|x|y|res|invariant");
while (x > 0) {
if (x % 2 == 0) {
y = 2 * y;
x = x / 2;
} else {
res = res + y;
y = 2 * y;
x = (x - 1) / 2;
}
invariant = y + 2;
String output = String.format("%d|%d|%d|%d|%d|%d", a,b,x,y,res,invariant);
System.out.println(output);
}
// < res = a + b >
}
Which gives the following output:
a|b|x|y|res|invariant
3|7|3|2|4|4
3|7|1|4|6|6
3|7|0|8|10|10
However, if I change the numbers, the invariant isn't equal to the res anymore. Therefore my loop invariant for this problem is not correct.
I'm struggling really hard to find the correct loop invariant and would be glad if there's any hint that someone can give me.
My first impression after looking into the code and my results is that the loop invariant changes based on a and b. Let's say both a and b are odd numbers as they are in my example, then my Loop invariant is correct (at least it seems like it)
Is it correct to assume a loop variant like the following?
< res = y - 2 && a % 2 != 0 && b % 2 != 0 >
I did use different numbers and it seems like anytime I change them there's a different loop invariant and I struggle to find any pattern whatsoever.
I would really appreciate if someone can give me a hint or a general idea on how to solve this.
Thanks
This loop computes the sum a+b.
res is initialized to a.
Then, in each iteration of the loop, the next bit of the binary representation of b (starting with the least significant bit) is added to res, until the loop ends and res holds a+b.
How does it work:
x is initialized to b. In each iteration you eliminate the least significant bit. If that bit is 0, you simply divide x by 2. If it's 1, you subtract 1 and divide by 2 (actually it would be sufficient to divide by 2, since (x-1)/2==x/2 when x is an odd int). Only when you encounter a 1 bit, you have to add it (multiplied by the correct power of 2) to the result. y Holds the correct power of 2.
In your a=3, b=7 example, the binary representation of b is 111
In the first iteration, the value of res is a + 1 (binary) == a + 1 = 4
In the second iteration, the value of res is a + 11 (binary) == a + 3 = 6
In the last iteration, the value of res is a + 111 (binary) == a + 7 == 10
You could write the invariant as:
invariant = a + (b & (y - 1));
This takes advantage of the fact the at the end of the i'th iteration (i starting from 1), y holds 2^i, so y - 1 == 2^i - 1 is a number whose binary representation is i 1 bits (i.e. 11...11 with i bits). When you & this number with b, you get the i least significant bits of b.
I'm changing some C code into Java, but I have come across a statement syntax that I have not seen before and I don't know what it means.
for (unsigned int i = 0; i < SIZE; i++)
{
count[2 * SIZE + 1] += grid[i][SIZE - 1 - i] != 0;
}
When adding elements of two arrays, I've never seen '!= 0' come after it. Do you know what this statement is doing? I can't find any reference to this online.
Any help is appreciated.
grid[i][SIZE - 1 - i] != 0 is a boolean expression which (by the C standard) is evaluated to 1 if the expression is true, 0 otherwise.
The same thing can be written as following:
for (unsigned int i = 0; i < SIZE; i++)
{
if ( grid[i][SIZE - 1 - i] != 0)
{
count[2 * SIZE + 1] += 1;
}
}
Unlike in C/C++, in Java, the result of this test is a boolean not an integer (0/1), and you cannot add a boolean so it counts for 0 for false or 1 for true.
I suggest a simple test which avoids to add 0 to count uselessly. So probably faster (well, constant branching could make it slower, has to be benched) & less cryptic (that's a fact), and valid in C, C++ or Java:
if (grid[i][SIZE - 1 - i] != 0)
{
count[2 * SIZE + 1]++;
}
Booleans can be implicitly converted to integers.
It is equivalent to
(grid[i][SIZE - 1 - i] != 0) ? 1 : 0
that is, add 1 if the condition is true and zero otherwise.
I'm writing a simple algorithm to check the primality of an integer and I'm having a problem translating this Java code into Python:
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
So, I've been trying to use this, but I'm obviously skipping the division by 3:
i = 3
while (i < int(math.sqrt(n))):
i += 2 # where do I put this?
if (n % i == 0):
return False
The only for-loop in Python is technically a "for-each", so you can use something like
for i in xrange(3, int(math.sqrt(n)), 2): # use 'range' in Python 3
if n % i == 0:
return False
Of course, Python can do better than that:
all(n % i for i in xrange(3, int(math.sqrt(n)), 2))
would be equivalent as well (assuming there's a return true at the end of that Java loop). Indeed, the latter would be considered the Pythonic way to approach it.
Reference:
for Statements
xrange
all
A direct translation would be:
for i in range(3, int(math.sqrt(n)), 2):
if n % i == 0:
return False
In a Java for loop, the step (the i += 2 part in your example) occurs at the end of the loop, just before it repeats. Translated to a while, your for loop would be equivalent to:
int i = 3;
while (i < Math.sqrt(n)) {
if (n % i == 0) {
return false;
}
i += 2;
}
Which in Python is similar:
i = 3
while i < math.sqrt(n):
if n % i == 0:
return False
i += 2
However, you can make this more "Pythonic" and easier to read by using Python's xrange function, which allows you to specify a step parameter:
for i in xrange(3, math.sqrt(n), 2):
if n % i == 0:
return False
Use a basic Python for i in range loop:
for i in range(3, math.round(math.sqrt(x)), 2):
if (n % i == 0):
return false
I get this answer from an automatic translation by AgileUML:
def op(self, n) :
result = False
i = 0
i = 3
while i < math.sqrt(n) :
if n % i == 0 :
return False
else :
pass
i = (i + 2)
return True
It seems to be semantically correct?
I have several small programs that require infinitely looping over the integer set Z sub n. I often write the code in this manor:
int x = 0;
int n = 13; //or some other prime
while(1) {
//do stuff dependent on x
++x;
x %= n;
}
I write code mostly in C/C++ & Java so I was wondering:
Is there a way to increment x mod n in one line rather then two in either language?
Have you considered:
x = (x + 1 == n ? 0: x + 1);
The chances are the x + 1 will optimise to one instruction and at least you are guaranteed to never use division (which a bad optimiser might use when % is involved).
x = (x + 1) % n;
Not terribly surprising.
Another alternative is this
x = ++x % n; // Java
if (++x == n) x = 0;
Using x = (x + 1 == n ? 0 : x + 1); requires two additions: one for the comparison and another when the value of x is set to x + 1.
I was looking at some code that outputs a number to the binary form with prepended 0s.
byte number = 48;
int i = 256; //max number * 2
while( (i >>= 1) > 0) {
System.out.print(((number & i) != 0 ? "1" : "0"));
}
and didn't understand what the i >>= 1 does. I know that i >> 1 shifts to the right by 1 bit but didn't understand what the = does and as far as I know, it is not possible to do a search for ">>=" to find out what it means.
i >>= 1 is just shorhand for i = i >> 1 in the same way that i += 4 is short for i = i + 4
EDIT: Specifically, those are both examples of compound assignment operators.