December 5th, 2012, 08:20 AM

Calculation
Hey,
Ok so today I need to calculate the shortest distance between 2 numbers in an array, given the array loops the end to the beginning, and likewise the beginning to the end. The array can contain endless amount of numbers.
Example:
PHP Code:
$numbers = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
The distance between 2 and 5 would be 3, and the distance between 9 and 2 would also be 3.
Im kind of stuck on this, and would very much appreciate the help.
Timmey
December 5th, 2012, 09:15 AM

What constitutes the distance? The array indices or the values? Perhaps your example should not have been sequential values that correspond to the index1.
There are 10 kinds of people in the world. Those that understand binary and those that don't.
December 5th, 2012, 09:35 AM

That is a very good question.The distance will increase by 1 for each element in the array, and not the actual values. I have found a solution in the meanwhile, if the values are sequential, and do not miss any values in between. However its not going to work as i need it to.
PHP Code:
$numbers = array( 1, 3, 7, 10, 30, 50, 90 );
In this case the distance between 7  30 would be 2 and 50  1 is also 2.
Current solution:
PHP Code:
$value1 = 2;
$value2 = 9;
$numbers = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$max = count( $numbers ) ;
$one = ( $max  $value1 + $value2 ) % $max;
$two = ( $max  $value2 + $value1 ) % $max;
$result = min( $one, $two );
Hope you can help me further.
December 5th, 2012, 09:39 AM

Originally Posted by Timmeyy
The distance will increase by 1 for each element in the array, and not the actual values.
Then your task makes no sense. The shortest distance between any two numbers would simply be 1 (or 0).
December 5th, 2012, 09:44 AM

No basically I want to count how many 'other' array elements I have to pass to get from value1 to value2, but you can walk both ways in the array like a loop.
Sorry if I dont make any sense.. hard to explain myself properly.
December 5th, 2012, 09:51 AM

So distance is represented by the indices with wrap. What are the inputs to the algorithm? I'm guessing the values. You first would need to find the indices for the corresponding values then get the difference. I did not try this but off the top of my head the wrap is the problem. If the difference is > $max/2, add the indices, take the modulo $max then add 1 since the indices are zero based.
There are 10 kinds of people in the world. Those that understand binary and those that don't.
December 5th, 2012, 09:54 AM

Sorry, I misunderstood you.
The distance between two values v1, v2 is simply
PHP Code:
min(abs($key1  $key2), count($numbers)  abs($key1  $key2));
With $key1 and $key2 being the keys of the values  use array_search() for that.
Comments on this post
December 5th, 2012, 10:05 AM

Originally Posted by Jacques1
PHP Code:
min(abs($key1  $key2), count($numbers)  abs($key1  $key2));
Worked perfectly. Thank you very much!