5
\$\begingroup\$

This is how I checkout to see if a number is in a range (in between two other numbers):

var a = 10,
    b = 30,
    x = 15,
    y = 35;

x < Math.max(a,b) && x > Math.min(a,b) // -> true
y < Math.max(a,b) && y > Math.min(a,b) // -> false

I have to do this math in my code a lot and I'm looking for shorter equivalent code.

This is a shorter version I came up with. But I am sure it can get much shorter:

a < x && x < b
true
a < y && y < b
false

But downside is I have to repeat x or y

\$\endgroup\$
4
  • 6
    \$\begingroup\$ a<x&x<b will return 1 or 0, and is 7 characters shorter. \$\endgroup\$
    – beary605
    Oct 10, 2012 at 1:16
  • 2
    \$\begingroup\$ For code-golf purposes beary605's solution is best, but if you're using the code a lot you'd be better off declaring a function like within(a,b) or inrange(a,b) somewhere in your code and using that. It's instantly obvious what it does and therefore easier to maintain in the future. \$\endgroup\$
    – Gareth
    Oct 10, 2012 at 11:19
  • \$\begingroup\$ beary605, your solution won't work because it will always return 0 when b<a even if x is in between a and b (for example when a=20; b=10; x=15) \$\endgroup\$
    – Yellos
    Oct 19, 2012 at 22:23
  • \$\begingroup\$ @Yellos a is supposed to be the minimum while b is max. Your example shows the minimum higher than the maximum! \$\endgroup\$
    – bryc
    Dec 30, 2016 at 22:52

3 Answers 3

13
\$\begingroup\$

13 chars, checks both variants a<b and b<a

(x-a)*(x-b)<0

In C may be used expression (may be also in JavaScript). 11 chars, No multiplications (fast)

(x-a^x-b)<0
\$\endgroup\$
9
\$\begingroup\$
a<x==x<b

JavaScript, 8 chars.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 0<0==0<1 -> false \$\endgroup\$
    – Mohsen
    Oct 20, 2012 at 0:28
  • \$\begingroup\$ I like Yellos answer. And 0>=0==0<1 returns true \$\endgroup\$
    – tim
    Jul 10, 2013 at 23:43
  • 1
    \$\begingroup\$ @Mohsen the OP's request was a number in between two limiting numbers, not including them. Therefore, 0<0==0<1 should return false, because in that case, 0 is the lower limit, but also the number that should be in between the range. And they are equal. \$\endgroup\$
    – gilad905
    Apr 10, 2017 at 14:16
3
\$\begingroup\$

JavaScript, 7 bytes

a<n&n<b
\$\endgroup\$
2
  • \$\begingroup\$ Golfed: a<n<b \$\endgroup\$
    – user85052
    Dec 12, 2019 at 12:49
  • 5
    \$\begingroup\$ @A̲̲ That doesn't work in Javascript \$\endgroup\$
    – Jo King
    Dec 12, 2019 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.