Problem:
Given three ints, a b c, one of them is small, one is medium and one is large. Return true if the three values are evenly spaced, so the difference between small and medium is the same as the difference between medium and large.
evenlySpaced(2, 4, 6) → true
evenlySpaced(4, 6, 2) → true
evenlySpaced(4, 6, 3) → false
Solution:
public boolean evenlySpaced(int a, int b, int c) { int[] anArray = {a, b, c}; Arrays.sort(anArray); int diffLow = anArray[1] - anArray[0]; int diffHi = anArray[2] - anArray[1]; if (diffLow == diffHi) return true; else return false; }
public boolean evenlySpaced(int a, int b, int c) {
ReplyDeleteif(b>a&&b>c&&a>c){
return b-a ==a-c;
}
if(a>b&&c>b&&a>c){
return a-c==c-b;
}
if(a>b&&c>a&&c>b){
return a-b==c-a; }
if(a==b&&b==a&&c==a&&b==c){
return true;
}
if (c>a&&c>b&&b>a){
return b-a==c-b;
}
return false;
}
public boolean evenlySpaced(int a, int b, int c) {
ReplyDeleteint[] anArray = {a, b, c};
Arrays.sort(anArray);
int diffLow = anArray[1] - anArray[0];
int diffHi = anArray[2] - anArray[1];
return diffLow == diffHi;
}
public boolean evenlySpaced(int a, int b, int c) {
ReplyDeletereturn isSpaced(a, b, c) || isSpaced(a, c, b) || isSpaced(c, b, a);
}
public boolean isSpaced(int a, int b, int c) {
return (a + b) == 2 * c;
}
above method is short and sweet but below is alternative for begineers.
ReplyDeleteif (a > b) { //e.g (4, 6, 2) : I would swap the value to arrange in descending order to find the small, medium large value for right difference
int temp = a; // temp == 4 && a == empty
a = b; // a == 2 && b == empty
b = temp; //b == 4
// now a and b are in descinding order : (4,2,6) == (2,4,6)
}
if (b > c){ //(4, 6, 2) is 6 > 2 ? yes
int temp = b; // temp = 6
b = c; // b = 2
c = temp; // c = 6
} // (4,6,2) == (4,2,6)
// now since b value is change, validate again a > b
if (a > b) { //e.g (4,2,6) :
int temp = a; // temp == 4 && a == empty
a = b; // a == 2 && b == empty
b = temp; //b == 4
// now a and b are in descinding order : (4,2,6) == (2,4,6)
}
return Math.abs(a-b) == Math.abs(b-c);
}
return b-a==c-b ? true: a-c==c-b ? true : b-a==a-c;
ReplyDeletepublic boolean evenlySpaced(int a, int b, int c) {
ReplyDeleteif(a+b==2*c || a+c==2*b || b+c==2*a){
return true;
}
return false;
}
public boolean evenlySpaced(int a, int b, int c) {
ReplyDeletereturn (a == c) && (a != b)
|| (a + b) == 2 * c
|| (b + c) == 2 * a
|| (c + a) == 2 * b;
}
public boolean evenlySpaced(int a, int b, int c) {
ReplyDeleteif (b < a) {
b = a ^ b;
a = a ^ b;
b = a ^ b;
}
if (b > c) {
c = b ^ c;
b = b ^ c;
c = b ^ c;
}
if (b < a) {
b = a ^ b;
a = a ^ b;
b = a ^ b;
}
return c - b == b - a;
}