in reply to Merge 2 strings like a zip
Just to show the crowd that I can, in fact, whip-up a “one-liner” ...
perl -e 'use strict; use warnings; my $a="ABCDE"; my $b="xyz"; my $res +ult=""; my $i; for ($i=0; $i<length($b); $i++) { $result .= substr($a +, $i, 1) . substr($b, $i, 1) }; $result .= substr($a, $i); print "$re +sult\n";'
If you really, really, know that one string is always shorter than the other, then this problem simply consists of taking a character from both strings until the shorter string is exhausted. Then, you append the remainder of the first (longer) string.
But I wouldn’t make such an assumption. I would allow either string to be longer:
use strict; use warnings; sub zip { my ($a, $b) = @_; my $result = ""; my $max = ( length($a) > length($b) ) ? length($a) : length($b); my $i; for ($i = 0; $i < $max; $i++) { if ($i < length($a)) { $result .= substr($a, $i, 1); } if ($i < length($b)) { $result .= substr($b, $i, 1); } } print "$result\n"; } zip("XYZZY", "ABC"); zip("ABC", "XYZZY"); zip("XYZZY", "XYZZY"); zip("", ""); . . . XAYBZCZY AXBYCZZY XXYYZZZZYY
“Elegant?” “Not?” My response is the same as Rhett Butler’s. The algorithm can be demonstrated to work in every case, by accompanying tests, and it is easy to eyeball it.
And, yes ... if I had any other reason to install and use an existing CPAN module that can zip a string, I would use that module. I probably would not install it, just to zip a string, since the alternative is trivial.
Replies are listed 'Best First'. | |
---|---|
Re^2: Merge 2 strings like a zip
by Anonymous Monk on Jul 11, 2015 at 20:02 UTC |