2010-10-28, 12:49 PM (This post was last modified: 2010-10-28, 03:07 PM by Nikkey.)
Fiel Wrote:In this problem, there are four possible pairings which would cause exceptions. Either the first and second number, second and third, or third and first are alike. Each of the following if statements checks if the others are pairs.
Spoiler
Code:
public int loneSum(int a, int b, int c) {
int sum = 0;
I'm sure there must be a faster way to do this as well because b^a is the same as a^b.
I see no reason as of why you need to xor first, then compare with >. This works perfectly fine, does the same thing and requires less computing power:
Spoiler
Code:
public int loneSum(int a, int b, int c) {
int sum = 0;
if(a!=b && a!=c)
sum += a;
if(b!=a && b!=c)
sum += b;
if(c!=a && c!=b)
sum += c;
return sum;
}
Faster approach is probably
Spoiler
Code:
public static int loneSum(int a, int b, int c) { // Sums up the numbers which does not equal to another number.
return a + b + c
+ (a==b?1:0) & (b==c?1:0) * a
- (a==b?1:0) | (a==c?1:0) * a << 1
- (b==c?1:0) * c << 1;
}
Since Java doesn't have proper low-level-code when coming to == > != < <= >=, I use fecking ternary.
Nevetheless, looks pretty ugly. Should use the most understandable loneSum.
For four, split it up more. You know you use repetitive patterns (diffAB <= 1), for example. Also, (! (diffAB <= 1)) == (diffAB >= 2).
Spoiler
Code:
public boolean closeFar(int a, int b, int c) {
boolean closeAB = isClose(a, b),
closeAC = isClose(a, c),
closeBC = isClose(b, c);
if (closeAB)
return (closeAC == closeBC && !closeAC);
else // We know that closeAB has to be false to get here, therefore closeAC and closeBC has to be different in order for this to produce the right answer.
return (closeAC != closeBC);
}
public boolean isClose(int a, int b){
return (Math.abs(a-b) <= 1);
}
Kalovale Wrote:Okay this is getting pretty petty of me, but I keep getting the impression that my approach isn't proper enough. It just seems somehow messy.
Spoiler
I have a favor though, regarding this problem:
The solution should be simple enough, but I can't seem to "call" the n from the fixTeen block to the main block to use. Also, I may not be thinking straight but how do I filter so that the outcome n satisfies certain conditions? I have been doing something along the lines of conditionals:
Code:
public int fixTeen(int n){
if( (n>=13) && (n<=19) && (n != 15) && (n != 16) )
return n;
}
But I can't test if it works correctly because of the problem above.
As of right now, fixTeen returns n if n is 13, 14, 17, 18 or 19. Otherwise, what does it return? What should it return?