I have two numbers: a and b. I want to put the smaller of them in one variable, and the larger in another variable (if they are equal, then any of them can be in any of the variables). Currently my code (in Javascript / Java) takes 7 lines:
if (a<=b) {
small = a;
large = b;
} else {
small = b;
large = a;
}
I could also use the Math.max and Math.min functions:
small = Math.min(a,b);
large = Math.max(a,b);
This takes only 2 lines but it is wasteful because the test of which one is larger will be done twice - once in Math.min and once in Math.max.
Is there a shorter / more elegant way to do this?
-
4\$\begingroup\$ Is this for Java or JavaScript? They're two different languages. \$\endgroup\$Jamal– Jamal2013年12月27日 08:02:59 +00:00Commented Dec 27, 2013 at 8:02
-
3\$\begingroup\$ Currently I need this for Javascript, but, the code for Java is the same. \$\endgroup\$Erel Segal-Halevi– Erel Segal-Halevi2013年12月27日 09:38:09 +00:00Commented Dec 27, 2013 at 9:38
-
5\$\begingroup\$ If you are seriously concerned about the performance penalty of doing two comparisons here, perhaps you should post a bigger chunk of code so we can inspect your whole algorithm for inefficiencies. \$\endgroup\$200_success– 200_success2013年12月27日 10:06:02 +00:00Commented Dec 27, 2013 at 10:06
-
2\$\begingroup\$ Micro-optimizations like these have little effect. I suggest you go for the 2-liner if you really want it short. \$\endgroup\$Joseph– Joseph2013年12月27日 10:08:47 +00:00Commented Dec 27, 2013 at 10:08
-
\$\begingroup\$ @200_success thanks, this is a good idea, I will do this one piece at a time.. \$\endgroup\$Erel Segal-Halevi– Erel Segal-Halevi2013年12月27日 11:34:17 +00:00Commented Dec 27, 2013 at 11:34
1 Answer 1
int t = a + b;
a = a > b ? t - a : a;
b = t - a;
// a is the small one
Or
small = a;
large = b;
if (a>b) {
small = b;
large = a;
}
But I think it will be shorter in Python:
if a > b:
a, b = b, a