Problem:
Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.
loneSum(1, 2, 3) → 6
loneSum(3, 2, 3) → 2
loneSum(3, 3, 3) → 0
Solution:
public int loneSum(int a, int b, int c) { if ( a == b && b == c) return 0; if (a == b) return c; if (b == c) return a; if (a == c) return b; else return a + b + c; }
public int loneSum(int a, int b, int c) {
ReplyDeleteif(a == b && b == c) {
return 0;
} else if(b == c) {
return a;
} else if(a == c) {
return b;
} else if(a == b) {
return c;
} else {
return a + b + c;
}
}
https://codingbatanswers.wordpress.com/logic-2/
ReplyDeletereturn(a==b&&b==c)?0:(a==b)?c:(a==c)?b:(b==c)?a:a+b+c;
ReplyDelete/*int sum = 0;
ReplyDeleteif (a !=b && b!=c && c!=a) {return sum = sum + a+b+c;}
if (a == b && b == c && c == a) {return sum;}
else if (a == b && b !=c) {return sum = sum + c;}
else if (b == c && c !=a) {return sum = sum + a;}
else if (c == a && b != c) {return sum = sum + b;}
return sum;
*/
Trying to refactor for arbitrary number of args. Is there are way to initialize the array to include all args, however many?
ReplyDelete--------------------------------------
int[] arr = {a,b,c}; //how to do this programatically?
int sum = 0;
for (int i = 0; i < arr.length; i++){
boolean flag = false;
for (int j=0; j<arr.length; j++){
if(i != j){
if (arr[i] == arr[j]){
flag = true;
}
}
}
if (!flag) sum += arr[i];
}
return sum;
i like this solution because it's dynamic
DeleteCame across this problem and decided to solve it in a functional way.
Deletepublic int loneSum(int...numbers) {
return Arrays.stream(numbers).map(n - > {
return Arrays.stream(numbers).filter(el - > {
return el == n;
}).count() > 1 ? 0 : n;
}).sum();
}
For my previous reply I used a formatter, which decided to space out the - and > in the lambdas. Sorry about that.
Deletepublic int loneSum(int a, int b, int c) {
ReplyDeleteif(a == b && b == c){
return 0;
}
if(b == c){
return a;
}
if(c == a){
return b;
}
if(a == b){
return c;
}
return a + b + c;
}
int sum=a+b+c;
ReplyDeleteif (a==b&&b==c){
return 0;
}
if (a==b){
return c;
}
if (b==c){
return a;
}
if (a==c){
return b;
}
else
return sum;
public int loneSum(int a, int b, int c) {
ReplyDeleteint num=0;
if(a==b && b==c)
return 0;
num =(a==b?c:b==c?a:a==c?b:a+b+c);
return num;
}
public int loneSum(int a, int b, int c) {
ReplyDeleteint sum = 0;
if (a == b && b == c) {
sum = 0;
} else if (a == b) {
sum = c;
} else if (b == c) {
sum = a;
} else if (a == c) {
sum = b;
} else {
sum = a + b + c;
}
return sum;
}