#!/usr/bin/perl -w

# use warnings;
use strict;

our ($casos,$puntos,$fixcost,$totdist,$cost, $i,$j,$k,
             @x0,@y0, @x,@y,@d, @r,@s,@c);
our $PRICESHORT = 0.12;               # transport from warehouses
our $PRICELONG = 0.05;              # transport from plant
our $MAXWAREHOUSES = 10;

$casos =200;
for $i (1..$casos){
        $x[$i] = -100 + 200*rand();
        $y[$i] = -100 + 200*rand();
        $d[$i] = 1000 * rand();            # demand
}
$fixcost = 5000;


$cost = 9e99;
for (;;){
        simulocaliz();
        evaluatedists();
        $j = evaluatecosts();
        if ($j < $cost){
            $cost=$j;
            print "\nSolutions:\n";
            for $i (1..$puntos){
                print $x0[$i]," ",$y0[$i],"\t->";
                for $k (1..$casos){
                        if ($s[$k]==$i){
                                print "$k, ";
                        }
                }
                print "<-\n";
            }
            print "Total distance is $totdist\n";
            print "Costs are $cost\n";
        }
}


sub simulocaliz {
        $puntos = 1+int rand($MAXWAREHOUSES);          # no. of warehouses
        @x0=@y0=();
        $x0[0]=0;
        $y0[0]=0;                        # the fixed coords of plant 
        for $i (1..$puntos){
                $x0[$i] = -100 + rand(200);
                $y0[$i] = -100 + rand(200);       
        }
}

sub evaluatedists {
        my ($m,$n);
        $totdist =0;
        for $i (1..$casos){
                $n=9e99;
                for $j (1..$puntos){
                        $m = sqrt(($x[$i]-$x0[$j])**2 + ($y[$i]-$y0[$j])**2);                        
                        if ($m<$n){
                                $n=$m;
                                $r[$i]=$m;
                                $s[$i]=$j;
                        }
                }
                $totdist += $r[$i];
        }
    for $i (1..$puntos){
	$totdist += sqrt(($x0[$i]-0)**2 + ($y0[$i]-0)**2);
    }
}

sub evaluatecosts {
        my ($k,$d)=(0,0);
        for $i (1..$casos){
                $c[$i] = $r[$i]*$d[$i]*$PRICESHORT;
                $k += $c[$i];
        }
        for $i (1..$puntos){
	    $d = sqrt(($x0[$i]-$x0[0])**2 + ($y0[$i]-$y0[0])**2 );
	    for $j (1..$casos){
		if ($s[$j]==$i){ $k += $d*$d[$j]*$PRICELONG; }    # long transport line
	    }
	}
        $k += $puntos * $fixcost;
        return $k;
}

__END__
