Closest-pair problem: Difference between revisions
m
→{{header|Perl}}: simplify, add output
SqrtNegInf (talk | contribs) (→{{header|Raku}}: refactored for clarity, 2x speed-increase as a bonus) |
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: simplify, add output) |
||
Line 3,181:
=={{header|Perl}}==
The divide & conquer technique is about 100x faster than the brute-force algorithm.
<lang perl>
use
use POSIX qw(ceil);
sub dist {
return
($a->[1] - $b->[1])**2 );▼
}
sub closest_pair_simple {
my ($a, $b, $d) = ( $points[0], $points[1], dist($points[0], $points[1]) );
▲ my $ra = shift;
my $
my $t = dist($p, $l);▼
▲ ($a, $b, $d) = ($p, $l, $t) if $t < $d;
}
}
sub closest_pair {
▲ my $r = shift;
▲ my @ay = sort { $a->[1] <=> $b->[1] } @$r;
}
sub closest_pair_real {
my ($rx, $ry) = @_;
▲ my $N = @xP;
return closest_pair_simple($rx) if scalar(@xP) <= 3;▼
my(@yR,
my $midx = ceil($N/2)-1;
my @
my
$_->[0] <= $xm ? push @yR, $_ : push @yL, $_ for @$ry;
▲ my $xm = ${$xP[$midx]}[0];
my @yR = ();▼
my ($al, $bl, $dL) = closest_pair_real(\@PL, \@yR);
my ($ar, $br, $dR) = closest_pair_real(\@PR, \@yL);
abs($xm - $_->[0]) < $closest and push @yS, $_ for @$ry;
for my
my
}
▲ my ( $w1, $w2, $closest ) = ($m1, $m2, $dmin);
▲ ($w1, $w2, $closest) = ($yS[$k], $yS[$i], $d) if $d < $closest;
▲ return ($w1, $w2, $closest);
}
printf "%.8f between (%.5f, %.5f), (%.5f, %.5f)\n", $_->[2], @{$$_[0]}, @{$$_[1]}
▲my @points = ();
{{out}}
<pre>0.00259322 between (-1.95541, -4.29695), (-1.95351, -4.29871)
0.00259322 between (-1.95541, -4.29695), (-1.95351, -4.29871)</pre>
▲ push @points, [rand(20)-10.0, rand(20)-10.0];
=={{header|Phix}}==
|