Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
1  
a<x&x<b will return 1 or 0, and is 7 characters shorter. – beary605 Oct 10 '12 at 1:16
2  
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. – Gareth Oct 10 '12 at 11:19
    
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) – Yellos Oct 19 '12 at 22:23

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
share|improve this answer
a<x==x<b

JavaScript, 8 chars.

share|improve this answer
1  
0<0==0<1 -> false – Mohsen Oct 20 '12 at 0:28
    
I like Yellos answer. And 0>=0==0<1 returns true – tim Jul 10 '13 at 23:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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