#!/usr/bin/perl -w

use 5.034;

$|++;

my $BigArea = 1000;
my ($X, $Y) = (0,0);
my $LittleA = 200;

# Se trata de hallar la longitud de una cuerda que ata a una vaca a un punto de la circunferencia 
# grande de 1000 m² y la permite pastar en una semicirfunferencia menor que reprensenta el 20% de
# la superficie de la primera, teniendo en cuenta que de la valla no puede pasar.

my $pi = 4 *atan2(1,1);
my $t0 = time();

my $Rmax = sqrt( $BigArea / $pi );
say "My Rmax = $Rmax";
say "Probe: Area for Rmax = ", $Rmax**2 * $pi ;


my $Rmin = sqrt ( 2 * $LittleA / $pi );
say "My Rmin = $Rmin";
say "Probe: Area for Rmin = " , $Rmin**2 * $pi /2;  

# if ( ($pi * $Rmin ** 2) / 2 > 400 ) {
#     die "Wrong guess";
# }

# my $lmax = $Rmin;
# say "Lmax = $lmax"; 

my ($c, $cc);
my $limity = $pi*$Rmax/2;    # a simple acelerator 

my $file = "metanohup_circles.out";
unless (-e $file){
    system "echo \> $file";
}
open IN, '<', $file or die $!;
my $i = <IN>;                                     # POSSIBLE BUG IN //= and //  v.5.038
chomp $i;
unless ($i){
    $i = $Rmin;
}
# my $in = $i // $Rmin;
# $in += 0;
close IN;

# Argumento fundamental: tengo una tarta de 200 m^2 le quito 2 cachos y DEBE de seguir teniendo 200,
# luego tengo que AÑADIR a Rmin trocitos para que me de 200 con la misma política de quitar cachitos
# sobre el semicírculo perfecto.

for (my $l = $i ;  ; $l += 0.00001){   # by hand, arbitrary precision. A millionth is too much
    $c = 0;
    $cc = 0.01;
    for (my $y = -$limity; $y <= 0; $y += 0.00001){  # se estudia una cuarta parte de los círculos 
	if ( sqrt(($X-$Rmax)**2 + ($y-0)**2) - sqrt(($Rmax-$l)**2 + ($y-0)**2) >= 0 ) { # the area in the semicircle-intersección is less 
	    # than the circunference of the grand circle and mayor than the small semicircle circunference
	    $c++;	
	}else{
	    $cc++;
	}
	print "\r$l $y";
	select (undef, undef, undef, 0.001);
    }
    if (($c/$cc) >= 100/250 && ($l * $l * $pi / 2 > 200)){    # si se estudiase la mitad del círculo debería ser 0.4, la proporción 200 de 0.5*1000
	# la duda es que al estudiar solo un cudrante simétrico, la proporcion buscada debería ser 0.1, no 0.2 que es la suma de dos cuadrantes
	# Solución: En un cudarante relevante debe haber 100 m², y el cuarto de círculo correspondiente es 250 m²-> ese es el ratio a buscar
	printf ("\n\n%.06f is the radio (or the lenght of the rope)!\n", $l);
	last;
    }
    system "echo $l \> $file";
}

unlink $file; # all clean for the next problem or precision

say "Time elapsed = ", (time()-$t0)/60, " minutes.";

exit 2;

__END__
  
The story of this puzzle is from the sexy influencer Jade,
  from UP AND ATOM. It resembles that crypto puzzles in which
  the only trick is formulate a simple problem with a complex 
  solution.
  
