Home: Fun With Perl: Perl Golf:
Strings-to-Array



Jasmine
Administrator / Moderator

Feb 18, 2002, 9:07 PM


Views: 46554
Strings-to-Array

Here's one from a great site, posted by our very own [ japhy ]. Spoiler at [url=http://perlmonks.org/index.pl?node_id=67973]http://perlmonks.org/index.pl?node_id=67973

Here's the goal: make a function that takes any number of equal-length strings, and returns an array of strings, where each string is the concatenation of the Nth character in each string.

Sample input: qw( jeff john mary )
Sample output: qw( jjm eoa fhr fny )

Here are my attempts:



Code
# 51 chars 
sub s2a{@_=@_;reverse+map{join"",map+chop,@_}1..length$_[0]}

# 51 chars
sub s2a{@_=@_;map{join"",map+s/(.)//s&&$1,@_}1..length$_[0]}

# 48 chars
sub s2a{map{join"",map+s/(.)//s&&$1,@_=@_}1..length$_[0]}

# 47 chars
sub s2a{map{join"",map{s/(.)//s;$1}@_=@_}1..length$_[0]}

# 45 chars
sub s2a{map{join"",map{s/.//s;$&}@_=@_}1..length$_[0]}




Jean
User


Feb 19, 2002, 5:07 AM


Views: 46545
Re: [Jasmine] Strings-to-Array

This is the first attempt at golf in my life... BlushBlushBlush

The offered solution surely is inferior to the offered solutions (score: 56),

but there might be some idea that will hopefully help somebody else to score better result Crazy

[perl]sub s2a{for(@a=@_){$_=split//;@r[$_-1].=shift@_ for 1..$_};@_=@r}[/perl]

No use to put it in the spoiler Frown


Jean Spector
SQA Engineer @ Exanet
jean.spector@softhome.net


There are only 10 types of people in the world -
Those who understand binary, and those who don't.


mhx
Enthusiast / Moderator

Feb 19, 2002, 2:20 PM


Views: 46538
Re: [Jasmine] Strings-to-Array

Just a minor improvement:


Code
# 41 chars 
map{join'',map{s/.//;$&}@_=@_}$_[0]=~/./g


Can we assume that the input strings do not contain newlines?
Then the /s modifier would not be neccessary.

-- mhx

At last with an effort he spoke, and wondered to hear his own words, as if some other will was using his small voice. "I will take the Ring," he said, "though I do not know the way."

-- Frodo