I have 2 variables A and B
if A =1 then B should B=2
and if A=2 then B should B=1
Like this, there are 3 pairs 1-2,3-4,5-6
What's the best way of making a code instead of just if-else
CodePudding user response:
It is possible to use simple addition and subtraction to get the other element of the two (x, x 1)
:
int a = 1; // the other is 2, sum is 3
int b = 3 - a; // if a = 2, b = 1
int c = 3; // the other is 4, sum is 7
int d = 7 - c; // if c = 4, d = 3
int m = 5; // the other is 6, sum is 11
int n = 11 - m;
Another approach could be using the following logic:
else b = a - 1
So, an array could be used to provide /- 1:
int[] signs = {-1, 1}
int b = a signs[a % 2];
a = 1, b = 2; a = 2, b = 1
a = 3, b = 4; a = 4, b = 3;
etc.
CodePudding user response:
One simple solution is a table lookup. In an array for each possible value of a
I store the corresponding value of b
:
private static final int[] B_PER_A = { -1, 2, 1, 4, 3, 6, 5 };
Since array indices always start at 0 in Java, we need to put a dummy value at index 0. This value is never used (or should never be, at least).
Let’s try it out:
for (int a = 1; a <= 6; a ) {
int b = B_PER_A[a];
System.out.format("a: %d; b: %d.%n", a, b);
}
Output:
a: 1; b: 2.
a: 2; b: 1.
a: 3; b: 4.
a: 4; b: 3.
a: 5; b: 6.
a: 6; b: 5.
Generalized to more than 3 pairs
If you need to handle a variable number of pairs, resort to math.
public static int calcB(int a) {
// 0-based index of pair (0 = 1-2, 1 = 3-4, etc.)
int pairNumber = (a - 1) / 2;
// a b for given pair
int pairSum = 4 * pairNumber 3;
int b = pairSum - a;
return b;
}
In each pair the sum is equivalent to 3 modulo 4. I am exploiting this fact in finding the sum for a given pair. When I subtract a
from that sum, I get b
. Let’s see that demonstrated too:
for (int a = 1; a <= 8; a ) {
int b = calcB(a);
System.out.format("a: %d; b: %d.%n", a, b);
}
a: 1; b: 2.
a: 2; b: 1.
a: 3; b: 4.
a: 4; b: 3.
a: 5; b: 6.
a: 6; b: 5.
a: 7; b: 8.
a: 8; b: 7.
The latter solution is more complicated and harder to read. So if you always have got three pairs, no more, no less, I recommend the simpler table lookup presented first.