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

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

by Athanasius (Archbishop)
on Dec 29, 2014 at 03:11 UTC ( [id://1111598]=note: print w/replies, xml ) Need Help??


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

Hello estreb,

This sounds like homework, so I’ll give advice rather than code. First, you need to nail down the requirements. What sort of output is wanted? If it’s just three separate lists, sorted according to the criteria, I would proceed as follows:

  1. Partition the array into two: (i) strings containing the letter “r” and (ii) all others.
  2. Partition array (ii) into two further arrays: (iii) strings starting with the letter “e” and (iv) all others.
  3. Sort array (i) alphabetically, ascending.
  4. Sort array (iii) using a sort routine that compares third characters alphabetically, ascending.
  5. Sort array (iv) using a sort routine that compares final characters alphabetically, descending.
  6. Output arrays (i), (iii), and (iv).

For (1) and (2), look at using grep or the part function from List::MoreUtils. For (3), just use sort. For (4) and (5), use sort together with a custom sort routine employing substr.

Now, there are parts of the specification that make me think the desired output may be more complicated than three separate sorted lists:

How do I “pick and choose” which items in the array I will sort, and make sure I leave the other items alone?

If you really do need to output a single array, with the original elements sorted “in place” and all interleaved back together (whatever that would really mean), a more complex approach will be needed. But any thought along those lines will be wasted effort until the specification has been clarified. As always, the best way to clarify a specification is to provide sample input together with the corresponding desired output (and this is just as important when talking to lecturers as when presenting problems to PerlMonks).

Hope that helps,

Update: fixed typo.

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-20 00:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found