While the OP specified that the second string is always the shortest, I wanted one that worked without that restriction:
#! perl -slw
use strict;
use Benchmark qw[ cmpthese ];
use List::MoreUtils qw[ zip ];
sub zipA {
my( $str1, $str2 ) = @_;
$str1 =~ s/.\K/ substr $str2, 0, 1, ''/gesr;
}
sub zipB {
no warnings qw/ uninitialized /;
my( $a, $b ) = @_;
my @a1 = split( '', $a );
my @a2 = split( '', $b );
return join'', zip @a1, @a2;
}
sub zipC($$){
my( $n, $a, $b ) = ( 1, @_ );
substr( $a, $n, 0, $_), $n += 2 for split '', $b;
return $a;
};;
sub zipR {
my ($s1, $s2) = @_;
my ($ls1, $ls2, $l, $tmp) = (length($s1), length($s2));
$l = $ls1<$ls2 ? $ls1 : $ls2;
$tmp = join("", map{substr($s1,$_,1), substr($s2,$_,1)} 0 .. $l-1)
. substr($l==$ls2 ? $s1 : $s2,$l);
return $tmp;
}
sub zipD {
my ($str1, $str2) = @_;
for (0 .. length $str2) {
substr $str1, $_ * 2 + 1, 0, substr $str2, $_, 1;
}
return $str1;
}
our $A = 'ABCDEFGHIJ';
our $B = 'abcde';
my (%tests,%results);
for my $T (qw(A B C D R)) {
$tests{$T.'a'} = "my \$z = zip$T( \$A, \$B )";
$tests{$T.'b'} = "my \$z = zip$T( \$B, \$A )";
my $a = eval($tests{$T.'a'});
my $b = eval($tests{$T.'b'});
}
my %R = ( a=>eval $tests{Ba}, b=>eval $tests{Bb} );
print "Expected: a=<$R{a}>, b=<$R{b}>";
for my $test (sort keys %tests) {
no warnings 'uninitialized';
my $S = eval $tests{$test};
my $R = $R{substr($test,1,1)};
if ($R ne $S) {
print "test $test failed: <$S>";
delete $tests{$test};
}
}
cmpthese -1, \%tests;
__END__
$ perl 1133865.pl
Expected: a=<AaBbCcDdEeFGHIJ>, b=<aAbBcCdDeEFGHIJ>
test Ab failed: <aAbBcCdDeE>
test Cb failed: <>
test Db failed: <>
Rate Bb Ba Aa Rb Ra Ca Da
Bb 105326/s -- 0% -62% -69% -69% -81% -86%
Ba 105326/s 0% -- -62% -69% -69% -81% -86%
Aa 276648/s 163% 163% -- -18% -19% -50% -62%
Rb 336364/s 219% 219% 22% -- -1% -39% -54%
Ra 339856/s 223% 223% 23% 1% -- -39% -54%
Ca 553781/s 426% 426% 100% 65% 63% -- -25%
Da 735965/s 599% 599% 166% 119% 117% 33% --
So I have the fastest one that works without that restriction. (Prediction, someone else will hold that title within 20 minutes......)
...roboticus
When your only tool is a hammer, all problems look like your thumb.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.