Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How to perform different sorts on multiple sections of items in the same array

by Anonymous Monk
on Dec 29, 2014 at 03:24 UTC ( [id://1111600]=note: print w/replies, xml ) Need Help??


in reply to How to perform different sorts on multiple sections of items in the same array

sort and How do I sort an array by (anything)?

Here's one way to do it with fairly complex sort criteria and a Schwartzian transform (assuming I've understood the requirements correctly):

#!/usr/bin/env perl use warnings; use strict; use List::Util 'shuffle'; use Test::More tests=>1; my @expect = qw/ frooc froof froz ebaz eyun ebxu quz qun que /; my @input = shuffle @expect; sub special { # sort routine used below $$a[1] <=> $$b[1] # first sort by categories or # then sort by the desired condition per category $$a[1]==1 ? $$a[0] cmp $$b[0] # category 1 (/r/) : ( $$a[1]==2 ? $$a[2] cmp $$b[2] # category 2 (/^e/) : $$b[3] cmp $$a[3] ) # category 3 (rest) } my @output = # sort with Schwartzian transform # Step 3: get back the orig_str out of the array map { $$_[0] } # Step 2: sort with the "special" function defined above sort special # Step 1: each item -> [orig_str, category, third_chr, last_chr] # where category is: /r/ => 1, /^e/ => 2, rest => 3 map { [$_, /r/?1:(/^e/?2:3), substr($_,2,1), substr($_,-1,1)] } @input; is_deeply \@output, \@expect or diag explain \@output;
  • Comment on Re: How to perform different sorts on multiple sections of items in the same array
  • Download Code

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-24 19:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found