Acme-Sort-Bozo
view release on metacpan or search on metacpan
lib/Acme/Sort/Bozo.pm view on Meta::CPAN
}
# Internal use, not exported. Verifies order based on $compare->().
sub is_ordered {
my ( $compare, $listref ) = @_;
ref( $compare ) =~ /CODE/
or croak "is_ordered() expects a coderef as first arg.";
ref( $listref ) =~ /ARRAY/
or croak "is_ordered() expects an arrayref as second arg.";
foreach( 0 .. $#{$listref} - 1 ) {
return 0
if $compare->( $listref->[ $_ ], $listref->[ $_ + 1 ] ) > 0;
}
return 1;
}
# Internal use, not exported. Simply swaps two random elements. The elements
# are guaranteed to be distinct.
sub swap {
my $listref = shift;
my $elements = @{$listref};
my $first = int( rand( $elements ) );
my $second;
do{ $second = int( rand( $elements ) ); } until $second != $first;
# ( $listref->[$first], $listref->[$second] ) = ( $listref->[$second], $listref->[$first] );
@{$listref}[$first, $second] = @{$listref}[$second, $first];
return $listref;
}
# Default compare() is ascending standard string comparison order.
sub compare {
croak "compare() requires two args."
unless scalar @_ == 2;
return $_[0] cmp $_[1];
}
t/00-load.t view on Meta::CPAN
"is_ordered() throws exception when not handed a coderef as first param."
);
undef $caught;
try {
Acme::Sort::Bozo::is_ordered( $compare, qw/ A B C D E / );
} catch { $caught = $_ };
like(
$caught,
qr/expects an arrayref/,
"is_ordered() throws an exception when not handed an arrayref as second param."
);
note "Testing Acme::Sort::Bozo::swap()";
my $listref = [qw/ A B C D E / ];
my $orig = join '', @{$listref};
my $new = join '', @{ Acme::Sort::Bozo::swap( $listref ) };
isnt( $new, $orig, "Swap successfully swapped two elements." );
( run in 1.498 second using v1.01-cache-2.11-cpan-39bf76dae61 )