Define range of value - java

I need to set an int variable in each iteration +-1, the range should be between 0-10. When i add 1 to 10 -> 0 when i add -1 to 0 -> 10. I know i need to go with modulo here but cannot find any solution.

This seems to easy, but if you really want to use modulo, did you try;
x = (x + y) % 11;
if (x < 0) x += 11;
or for "ultimate readability" and probably still better performance just
x = x + y;
if (x < 0) x += 11;
if (x > 11) x -= 11;
Please note that the requirements locks y down to being -1 or 1.

Related

How do I check divisibility in Java?

I am trying to check if on number is divisible by another, and currently I use this method:
int x = 70;
int y = 30;
if(x/y == Math.round(x/y)) {
...
}
Is there a simpler way?
You can use modulus operator like this in your condition,
if (x%y == 0)
A good way is to use modulus operator, which returns the remainder after dividing by a number, e.g.
5 % 2 = 1 (1 is the remainder after 5 is divided by 2)
So for a number to be divisible by another, it should have a remainder of 0 (i.e. x % y = 0)
if (x % y == 0)
{
//x is divisible by y
}
else
{
//x is not divisible by y
}

Increment X Mod N in One Line

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.

How to re-implement sin() method in Java ? (to have results close to Math.sin() )

I know Math.sin() can work but I need to implement it myself using factorial(int) I have a factorial method already below are my sin method but I can't get the same result as Math.sin():
public static double factorial(double n) {
if (n <= 1) // base case
return 1;
else
return n * factorial(n - 1);
}
public static double sin(int n) {
double sum = 0.0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum += Math.pow(1, i) / factorial(2 * i + 1);
} else {
sum += Math.pow(-1, i) / factorial(2 * i + 1);
}
}
return sum;
}
You should use the Taylor series. A great tutorial here
I can see that you've tried but your sin method is incorrect
public static sin(int n) {
// angle to radians
double rad = n*1./180.*Math.PI;
// the first element of the taylor series
double sum = rad;
// add them up until a certain precision (eg. 10)
for (int i = 1; i <= PRECISION; i++) {
if (i % 2 == 0)
sum += Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
else
sum -= Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
}
return sum;
}
A working example of calculating the sin function. Sorry I've jotted it down in C++, but hope you get the picture. It's not that different :)
Your formula is wrong and you are getting a rough result of sin(1) and all you're doing by changing n is changing the accuracy of this calculation. You should look the formula up in Wikipedia and there you'll see that your n is in the wrong place and shouldn't be used as the limit of the for loop but rather in the numerator of the fraction, in the Math.pow(...) method. Check out Taylor Series
It looks like you are trying to use the taylor series expansion for sin, but have not included the term for x. Therefore, your method will always attempt to approximate sin(1) regardless of argument.
The method parameter only controls accuracy. In a good implementation, a reasonable value for that parameter is auto-detected, preventing the caller from passing to low a value, which can result in highly inaccurate results for large x. Moreover, to assist fast convergence (and prevent unnecessary loss of significance) of the series, implementations usually use that sin(x + k * 2 * PI) = sin(x) to first move x into the range [-PI, PI].
Also, your method is not very efficient, due to the repeated evaluations of factorials. (To evaluate factorial(5) you compute factorial(3), which you have already computed in the previous iteration of the for-loop).
Finally, note that your factorial implementation accepts an argument of type double, but is only correct for integers, and your sin method should probably receive the angle as double.
Sin (x) can be represented as Taylor series:
Sin (x) = (x/1!) – (x3/3!) + (x5/5!) - (x7/7!) + …
So you can write your code like this:
public static double getSine(double x) {
double result = 0;
for (int i = 0, j = 1, k = 1; i < 100; i++, j = j + 2, k = k * -1) {
result = result + ((Math.pow(x, j) / factorial (j)) * k);
}
return result;
}
Here we have run our loop only 100 times. If you want to run more than that you need to change your base equation (otherwise infinity value will occur).
I have learned a very good trick from the book “How to solve it by computer” by R.G.Dromey. He explain it like this way:
(x3/3! ) = (x X x X x)/(3 X 2 X 1) = (x2/(3 X 2)) X (x1/1!) i = 3
(x5/5! ) = (x X x X x X x X x)/(5 X 4 X 3 X 2 X 1) = (x2/(5 X 4)) X (x3/3!) i = 5
(x7/7! ) = (x X x X x X x X x X x X x)/(7 X 6 X 5 X 4 X 3 X 2 X 1) = (x2/(7 X 6)) X (x5/5!) i = 7
So the terms (x2/(3 X 2)) , (x2/(5 X 4)), (x2/(7 X 6)) can be expressed as x2/(i X (i - 1)) for i = 3,5,7,…
Therefore to generate consecutive terms of the sine series we can write:
current ith term = (x2 / ( i X (i - 1)) ) X (previous term)
The code is following:
public static double getSine(double x) {
double result = 0;
double term = x;
result = x;
for (int i = 3, j = -1; i < 100000000; i = i + 2, j = j * -1) {
term = x * x * term / (i * (i - 1));
result = result + term * j;
}
return result;
}
Note that j variable used to alternate the sign of the term .

Complex code/algorithm optimization (e.g. simplification) quandary

How can this code be simplified?
if (x == 0) x = 1;
else if (x == 1) x = 0;
else if (x == 2) x = 3;
else if (x == 3) x = 2;
If x is always between 0 and 3 then try this:
x ^= 1;
It toggles the least significant bit.
If x can be a value other than between 0 to 3 then you can first test for that:
if (x >= 0 && x <= 3) {
x ^= 1;
}
This is the simplest form possible:
if (x == 0) x = 1;
else if (x == 1) x = 0;
else if (x == 2) x = 3;
else if (x == 3) x = 2;
wait... that's exactly your code.
cryptic one liners are NOT simple.
You could use something like this:
int mymap[4] = {1,0,3,2};
and then in your code use this:
x = mymap[x];
To use your pseudocode notation, maybe:
if (x % 2 == 0) x = x + 1
else x = x - 1
e.g you are adding one if it is an even number, subtracting otherwise? In terms of optimization though, I don't see what is particularly slow or wrong with your original code.
if(x >= 0 && x <= 3)
if((x%2) != 0) //odd
x--;
else if((x%2) == 0) //even
x++;
Not that I think this is simpler, and it doesn't limit the case to 0..3, but:
x += (x % 2 == 0) ? 1 : -1;
x ^= x & ~3 == 0 ? 1 : 0;
Unfortunately my code was so simplified it failed to make the 30-character minimum...
A common approach for handling simple data like this is to use the switch statement.
The code would be more redable with a switch statement:
switch(x) {
case 0: x=1: break;
case 1: x=0: break;
case 2: x=3: break;
case 3: x=2; break;
}
However, it's just about code readbility, not algorithmics, nor optimization.
x^=1;
unless x can be lower than 0 or higher than 3, which the problem specification doesn't state.
if( 0 <= x && x <= 3 )
x ^= 1;
if ( x >>> 2 == 0 )
{ x ^= 1;
}
one liner:
x=(x==0)?1:((x==1)?0:(x==2)?3:(x==3)?2:x);
The best way to do this...
if(x % 2 == 0){
x = +x;
}else{
x = -x;
}
Probably using switch statements

Why do I get -1 from this statement?

if(heading == 2){
nextY = (y-1) % 20;
nextX = x;
}
When debugging this program, my heading is 2 and y = 0, however, when I come to this if statement, nextY becomes -1. Why is it not cycling properly? (0-19)?
That's how mod operation generally works for negative numbers in programming (in all languages I tried it in).
But you can easily make number positive before doing mod
nextY = (y + 20 - 1) % 20;
Modulo operators often return negative numbers for negative inputs. For example, C# will give you a number from -356..359 for the expression x % 360.
Instead of subtracting 1 then taking modulo 20, you can add 19, which is the same thing but keeps the number positive, or you can use the ternary operator:
nextY = (y+19) % 20; // or
nextY = (nextY == 0) ? 19 : nextY - 1;

Categories