#!/usr/bin/perl
#
# hashswap.pl
print "\n\nThis program selects a random combination\n";
print "\tof k elements out of 1..n.\n\n";
print "Enter max ==> ";
chomp($n=<>); $m=$n+1;
print "Enter the combination size ==> ";
chomp($k=<>);
print "\n\n";
$start = times();
use integer;
for (1..$k)
{ $v = $_ + int(rand($m-$_));
if(!($w=$h{$v})) { $w = $v }
if(!($s=$h{$_})) { $s = $_ }
$h{$_}=$w; $h{$v}=$s ### swap
}
no integer;
$endT = times();
use integer;
for (1..$k) { print " $h{$_}" }
no integer;
print "\n\n\tcomputation time: ", $endT-$start, "\n\n";
# Koniec programu
Algorytm zawiera się głównie w pierwszej pętli, której tekst składa się w sumie z 6 linijek. Gdy chce ktoś mierzyć czas dla wielkich parametrów, to linijki pomiędzy instrukcją:
$endT = times();
oraz instrukcją print, może usunąć (lub zakomentować).
A teraz podam ten sam program, tyle że swap będzie dokonany w stylu wczesnego minikomputera PDP:
#!/usr/bin/perl
#
# pdpswap.pl
print "\n\nThis program selects a random combination\n";
print "\tof k elements out of 1..n.\n\n";
print "Enter max ==> ";
chomp($n=<>); $m=$n+1;
print "Enter the combination size ==> ";
chomp($k=<>);
print "\n\n";
$start = times();
use integer;
for (1..$k)
{ $v = $_ + int(rand($m-$_));
if(!$h{$_}) { $h{$_} = $_ }
if($v != $_)
{ if(!$h{$v}) { $h{$v} = $v }
$h{$v} ^= $h{$_} ^= $h{$v} ^= $h{$_} ### swap
} }
no integer;
$endT = times();
use integer;
for (1..$k) { print " $h{$_}" }
no integer;
print "\n\n\tcomputation time: ", $endT-$start, "\n\n";
# Koniec programu