Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Using map function to print few elements of list returned by sort function

by Laurent_R (Parson)
on May 25, 2014 at 15:10 UTC ( #1087363=note: print w/ replies, xml ) Need Help??


in reply to Using map function to print few elements of list returned by sort function

I agree with what other monks have said, i.e. that it is probably not a very good idea to make things more complicated by trying to make them as compact as possible. However, for the sake of the exercise, this is possible one-liner (well, really a two-liner) to do what you want:

perl -F: -nale ' push @d, [@F]; END { print join "\n", map { join ":" +, @$_} grep { $c = $$_[1] eq $prec? $c+1:1; $prec = $$_[1]; $c>4? 0: 1} sort + {$a->[1] cmp $b->[1] || $b->[0] <=> $a->[0]} @d;};' file.txt
Note that it is also sorting the input by country in the event that the input is not grouped by country. The following is an example execution, piping your reshuffled input data (not grouped by country) into the Perl script:
$ echo '20470:ZM:Samfya:Africa > 61739:ZW:Chinhoyi:Africa > 20149:ZM:Sesheke:Africa > 26459:ZW:Beitbridge:Africa > 37423:ZW:Bindura:Africa > 18638:ZM:Siavonga:Africa > 699385:ZW:Bulawayo:Africa > 47294:ZW:Chegutu:Africa > 18860:ZW:Chipinge:Africa > 28205:ZW:Chiredzi:Africa > ' | perl -F: -nale ' push @d, [@F]; > END { print join "\n", map { join ":", @$_} > grep { $c = $$_[1] eq $prec? $c+1:1; $prec = $$_[1]; $c>4? 0: 1} > sort {$a->[1] cmp $b->[1] || $b->[0] <=> $a->[0]} @d;}' 20470:ZM:Samfya:Africa 20149:ZM:Sesheke:Africa 18638:ZM:Siavonga:Africa 699385:ZW:Bulawayo:Africa 61739:ZW:Chinhoyi:Africa 47294:ZW:Chegutu:Africa 37423:ZW:Bindura:Africa
Edit 15:33 UTC: I posted my final result above only a few hours after I started to look for a solution because I had to interrupt my work on it for family obligations. I had not seen your solution using splice, it is better than my grep solution. Overall, I spent probably about 45 minutes to get it (hopefully) right, writing a solution with regular while or for loops would have probably taken less than a third of that time.


Comment on Re: Using map function to print few elements of list returned by sort function
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (14)
As of 2014-10-21 12:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (103 votes), past polls