#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

#### Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmers Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use it's exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

# a tiny problem

Posts: 13Member
As the following picture:
It's a circle that is consist of the numbers,how can i simply calculate the distance between some tow numbers,for example,5 and 8 is 3;22 and 2 is 4 ???????????
0 1 2 3 4 5
23 6
22 7
21 8
20 9
19 10
18 11
17 16 15 14 13 12

· ·

• Posts: 39Member
The short answer in Python is

lambda a, b, size: min((a - b) % size, (b - a) % size)

where a and b are inputs and size is the number of elements (24 for this case).

The slightly longer answer is
SIZE = 24

def dis(a, b):
d1 = (a - b) % size
d2 = (b - a) % size
return min(d1, d2)

And, if you don't like modular arithmetic,
SIZE = 24

def dis2(a, b):
high = max(a, b)
low = min(a, b)
dis1 = high - low
dis2 = SIZE - dis1
return min(dis1, dis2)

That one only works for values of a and b in range(0, 24), but it saves you the trouble of having to understand modular arithmetic. ;)
· ·
• Posts: 13Member
The slightly longer answer is
SIZE = 24

def dis(a, b):
d1 = (a - b) % size
d2 = (b - a) % size
return min(d1, d2)
-----------------------
It dosen't work:
a=22,b=2
d1=(22-2)%24 = 20
d2=(2-22)%24 = -20
min(d1,d2)=20 is not the right answer 4?!!!!!??!!?!
· ·
• Posts: 39Member
(2 - 22) = -20
-20 % 24 = 4
Bear in mind that % returns the remainder of the division of its arguments.
· ·
• Posts: 13Member
-20%24=4???How do calculate that?!Is it not -20?!
· ·
• Posts: 39Member
No, that's the mod operator. So,
-20 % 24 is equivalent to -20 mod 24 (in psuedo code).
If you are questioning the math behind it, here is the complicated answer: http://en.wikipedia.org/wiki/Modular_arithmetic

Consider:
52 % 24 = 4
28 % 24 = 4
4 % 24 = 4
-20 % 24 = 4

52 = 2 * 24 +4
28 = 1 * 24 + 4
4 = 0 * 24 + 4
-20 = -1 * 24 + 4
· ·