Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Merge 2 strings like a zip

by sundialsvc4 (Abbot)
on Jul 09, 2015 at 11:50 UTC ( [id://1133945]=note: print w/replies, xml ) Need Help??


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
    Elegance arises from the concise use of existing and suitable features to achieve the desired effect. Ideally, at least in my view, the solution to the problem can be stated in a declarative rather than a procedural fashion.
    While I would concede that the former is not necessarily more concise, its implicit usage of features required to solve the problem will contribute to the elegance of the solution put forward. Solutions involving an explicit loop stepping through a string character-by-character hence certainly are transparent to inspection ... but way too procedural to be surprising or elegant.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1133945]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (10)
As of 2024-04-23 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found