Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Sorting strings

by ozone (Friar)
on Aug 30, 2001 at 16:16 UTC ( #109051=note: print w/replies, xml ) Need Help??


in reply to Sorting strings

you can use the clever form of sort:
my @normalTimes = ('+1h6m', '0h13m', '-4h10m', '-6h5m'); my @sortedTimes = sort { getMinutes($b) <=> getMinutes($a) } @normalTi +mes; sub getMinutes { my($hour,$minute) = split(/[hm]/, shift); return( ($hour * 60) + (($hour > 0) ? $minute : -$minute)); }
UPDATE: fixed typos & sub error (thanks Hofmator)

Replies are listed 'Best First'.
Re: Re: Sorting strings
by Hofmator (Curate) on Aug 30, 2001 at 16:36 UTC

    Some things go wrong with your code

    • typos: substitute the braces after getMinutes with normal parentheses
    • getMinutes doesn't calculate correctly:
      -1h10m => -50 # correct -70 -1h20m => -40 # correct -80
      so the sorting is not correct.
    • You are calculating the getMinutes values more than once per entry. See my solution elsewhere in this thread for a way to cache these results.

    -- Hofmator

      I'd be hesitant to say that running that calculation more than once per value is something "wrong" with the code--as was pointed out to me by jeroenes, for sorting a small number of elements, the Schwartzian doesn't buy you anything significant (especially for a cheap calculation like this one). Of course, if N gets larger, then the benefits of using it increase, so ++ for posting it: I just don't think it's necessarily called for here.



      If God had meant us to fly, he would *never* have given us the railroads.
          --Michael Flanders

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2022-05-21 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (76 votes). Check out past polls.

    Notices?