Algorithms

Moderators: None (Apply to moderate this forum)
Number of threads: 384
Number of posts: 762

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
a tiny problem Posted by zydgyy on 9 Oct 2009 at 1:22 AM
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

Report
Re: a tiny problem Posted by bubbatremell on 15 Oct 2009 at 3:24 PM
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. ;)
Report
Re: a tiny problem Posted by zydgyy on 15 Oct 2009 at 7:46 PM
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?!!!!!??!!?!
Report
Re: a tiny problem Posted by bubbatremell on 16 Oct 2009 at 10:42 AM
(2 - 22) = -20
-20 % 24 = 4
Bear in mind that % returns the remainder of the division of its arguments.
Report
Re: a tiny problem Posted by zydgyy on 17 Oct 2009 at 8:41 PM
-20%24=4???How do calculate that?!Is it not -20?!
Report
Re: a tiny problem Posted by bubbatremell on 22 Oct 2009 at 12:48 PM
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



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.