Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Schwartzian Transform

by chromatic (Archbishop)
on Dec 25, 1999 at 09:21 UTC ( [id://1394]=perlcraft: print w/replies, xml ) Need Help??

   1: #Want to sort a complex data structure by some element
   2: #efficiently?  For example, how do you sort an array
   3: #of strings by their length?  Use the transform:
   4:    @sorted = map { $_->[1] }
   5:    sort { $a->[0] <=> $b->[0] }
   6:    map { [ length $_, $_ ] } @strings;
   7: 
   8: #Confused?  Put in temporary arrays, 
   9: #just to see what we're doing.
  10: 
  11: # create a temporary array of anonymous arrays
  12: # (0: length of the string, 1: the string)
  13:    @temp = map { [ length $_, $_ ] } @strings;
  14: # sort by length
  15:    @temp = sort { $a->[0] <=> $b->[0] };
  16: # grab just the strings and put them in @ordered
  17:    @sorted = map { $_->[1] } @temp;
  18: 
  19: #Knowing the context of certain operations
  20: # and being able to chain them together
  21: # is crucial to a deep and idiomatic
  22: # understanding of Perl.

Replies are listed 'Best First'.
Re: Schwartzian Transform
by I0 (Priest) on Jan 02, 2001 at 18:06 UTC
    You probably meant @temp = sort { $a->[0] <=> $b->[0] } @temp;

    Although, given a @temp array, it benchmarks faster to do
    @temp = map { length $_ } @strings; @sorted = @strings[sort{$temp[$a]<=>$temp[$b]} $[..$#temp];

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 pondering the Monastery: (6)
As of 2024-12-02 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found