Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function p($x,$y){ return Array('x'=>$x,'y'=>$y); }
- $points=Array(
- p(-8940.48,-51.5397),
- p(-8818.05,-69.5144),
- p(-8991.14,-250.521),
- p(-8795.79,-79.0435),
- p(-8829.54,-98.7120),
- p(-8786.79,-154.691),
- p(-8969.07,-80.9248),
- p(-8932.77,-274.706),
- p(-8980.23,-70.8425),
- p(-8858.29,-83.8734)
- );
- function shorter_distance(&$points){
- $shorted=Array();
- //I'll go ahead and say the first point is the starting point.
- //no need to make this crazy complicated
- $curpoint=array_shift($points);
- $shorted[]=$curpoint;
- while(!empty($points)) {
- $addpoint=0;
- $min_d=$d=0;
- foreach($points as $k=>$v){
- if($min_d||$min_d<($d=dist($v,$curpoint))) {
- $min_d=$d;
- $addpoint=$k;
- }
- }
- $shorted[]=$points[$addpoint];
- array_splice($points,$addpoint);
- }
- $points=$shorted;
- }
- function compute_travel_distance($points){
- $distance=0;
- for($x=1;$x<count($points);$x++) {
- $distance+=dist($points[$x],$points[$x-1]);
- }
- return $distance;
- }
- function dist($p1,$p2){
- return sqrt(pow($p1['x']-$p2['x'],2)+pow($p1['y']-$p2['y'],2));
- }
- echo "Travel distance before: ".compute_travel_distance($points)."\n";
- shorter_distance($points);
- echo "Travel distance after: ".compute_travel_distance($points)."\n";
- ?>
Add Comment
Please, Sign In to add comment