Guest User

Untitled

a guest
Jun 19th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.26 KB | None | 0 0
  1. <?php
  2.  
  3. function p($x,$y){ return Array('x'=>$x,'y'=>$y); }
  4.  
  5. $points=Array(
  6.     p(-8940.48,-51.5397),
  7.     p(-8818.05,-69.5144),
  8.     p(-8991.14,-250.521),
  9.     p(-8795.79,-79.0435),
  10.     p(-8829.54,-98.7120),
  11.     p(-8786.79,-154.691),
  12.     p(-8969.07,-80.9248),
  13.     p(-8932.77,-274.706),
  14.     p(-8980.23,-70.8425),
  15.     p(-8858.29,-83.8734)
  16. );
  17.  
  18. function shorter_distance(&$points){
  19.     $shorted=Array();
  20.  
  21.     //I'll go ahead and say the first point is the starting point.
  22.     //no need to make this crazy complicated
  23.     $curpoint=array_shift($points);
  24.     $shorted[]=$curpoint;
  25.    
  26.     while(!empty($points)) {
  27.         $addpoint=0;
  28.         $min_d=$d=0;
  29.         foreach($points as $k=>$v){
  30.             if($min_d||$min_d<($d=dist($v,$curpoint))) {
  31.                 $min_d=$d;
  32.                 $addpoint=$k;
  33.             }
  34.         }
  35.         $shorted[]=$points[$addpoint];
  36.         array_splice($points,$addpoint);
  37.     }
  38.    
  39.     $points=$shorted;
  40. }
  41.  
  42. function compute_travel_distance($points){
  43.     $distance=0;
  44.     for($x=1;$x<count($points);$x++) {
  45.         $distance+=dist($points[$x],$points[$x-1]);
  46.     }
  47.     return $distance;
  48. }
  49.  
  50. function dist($p1,$p2){
  51.     return sqrt(pow($p1['x']-$p2['x'],2)+pow($p1['y']-$p2['y'],2));
  52. }
  53.  
  54.  
  55. echo "Travel distance before: ".compute_travel_distance($points)."\n";
  56. shorter_distance($points);
  57. echo "Travel distance after: ".compute_travel_distance($points)."\n";
  58.  
  59.  
  60. ?>
Add Comment
Please, Sign In to add comment