Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Hmm. I just realized there's another interpretation of the question that might be more valid than my other solution.

Suppose the question means: given elements of @list2 which begin with the letters of @list, rearrange them so that the beginning letters are sorted in that order. Thus, the length of @list2 in no way correlates with the length of @list, and this was merely a concidence in the sample set.

To that, I'll have to add two arbitrary decisions: if the word doesn't begin with one of the letters, put it first, and within a given initial letter, sort alphabetically.

The code for that would look like this:

my %mapping; @mapping{@list} = 1..@list; my @rearranged = map { $_->[0] } sort { $a->[1] <=> $b->[1] or $a->[0] cmp $b->[0] } map { [$_, $mapping{substr($_,0,1)} || 0] } @list2;
There. One of them there, Schwartzian thingies.

And yes, I see other similar solutions in this thread, but I bet those repeated index() calls inside the sort comparator are gonna make it doggy slow for dozens of elements. By caching the reverse map, as well as the sort position, we save mondo time.

-- Randal L. Schwartz, Perl hacker


In reply to Re: sorting based on a list by merlyn
in thread sorting based on a list by mbond

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2024-04-24 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found