in reply to Sorting array by number of occurences of a char

Use tr/// to count the commas and use a Schwartzian Transform to limit the amount of work that has to be done.

#!/usr/bin/perl my @unsorted = qw(a,b,c c,b,a a,a,a,a b,b); my @sorted = map { $_->[1] } sort { $b->[0] <=> $a->[0] } map { [ tr/,// , $_ ] } @unsorted; print "@sorted\n"
-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re: Re: Sorting array by number of occurences of a char
by zigdon (Deacon) on Oct 04, 2002 at 15:26 UTC

    Gah, sauoq beat me to it. This is the famous Schwartzian Transform. If this is your 5th perl script, it's time you start using it! :)

    Update: Either I'm blind, or saouq has edited his node. This node serves no purpose now :)

    -- Dan

      Either I'm blind, or saouq has edited his node. This node serves no purpose now :)

      Yes, zigdon, you caught me. Originally I just pasted my quick one-liner in and hit submit instead of preview.

      Your node does serve a purpose though. You have that nice little link that explains the ST very thoroughly. :-)

      This was the text of the node when zigdon first saw it:

      $ perl -le '@unsorted = qw(a,b,c c,b,a a,a,a,a b,b); @sorted = map { $ +_->[1] } sort { $b->[0] <=> $a->[0] } map { [tr/,// , $_] } @unsorted +; print "@sorted"' a,a,a,a a,b,c c,b,a b,b
      -sauoq
      "My two cents aren't worth a dime.";