On 10/3/05, Bakken, Luke <[EMAIL PROTECTED]> wrote:
> JupiterHost.Net wrote:
> >> On Oct 3, JupiterHost.Net said:
> >>
> >>> I have a list of strings that start with an uppercase B, Q, or Z
> >>>
> >>> I need to sort them so they are in order of Q, B , then Z
> >>>
> >>> Any ideas or input on how to efficiently do that with sort() or even
> >>> map() is most appreciated :) perldoc -f sort|-f map didn't appear to
> >>> address this situation :(
> >
> > Jeff 'japhy' Pinyan wrote:
> >
> >> I would use map() before and after sort() to "correct" leading
> >> characters.
> >>
> >> my @sorted =
> >> map { tr/123/QBZ/; $_ }
> >> sort
> >> map { tr/QBZ/123/; $_ }
> >> @data;
> >
> > Xavier Noria wrote:
> >
> > > They all go in ASCII relative order except B <-> Q, thus a way to
> > get > it is to handle that special case and delegate to cmp the rest:
> > >
> > > my @sorted = sort {
> > > my $x = substr($a, 0, 1) . substr($b, 0, 1);
> > > $x eq "BQ" || $x eq "QB" ? $b cmp $a : $a cmp $b;
> > > } @array;
> > >
> > > I used the concatenation for clarity, you see the idea anyway if
> > that's > too expensive for your usage.
> >
> > Brilliant! I'll benchmark those ideas :) Thanks you two!
>
> Read this for an explanation of Jeff's solution:
>
> http://en.wikipedia.org/wiki/Schwartzian_transform
>
Sort of. Perhaps Randy will chime in here, but as I understand it, the
key to the Schwartzian transform is that the input data 1) doesn't
undergo direct comparison, and 2) is passed by reference, speeding up
the sort, so:
my @sorted =
map { $_->[0] }
sort { $a->[1] cmp $b[1] }
map { [$_, s/^(.)/$1 eq "Q" ? 1 :
($1 eq "B" ? 2 :
($1 eq "Z" ? 3 : $1))/ex] }
@original;
That will slow you down a little with the capturing and substitution,
but is solves Jeff's problem with capital Q, B, or Z later in the
string. I'm not sure how it stacks up to Xaiver's temp variable and
multiple substr calls. This isn't as simple as it looked.
HTH,
-- jay
--------------------------------------------------
This email and attachment(s): [ ] blogable; [ x ] ask first; [ ]
private and confidential
daggerquill [at] gmail [dot] com
http://www.tuaw.com http://www.dpguru.com http://www.engatiki.org
values of β will give rise to dom!