in reply to Is it possible to make reference to substrings and sort them?

Using chop could be another way to go.

$ perl -Mstrict -Mwarnings -E ' say join q{}, map { substr $_, -1 } sort sub { my $s = shift; my @r; push @r, do { $s = chop( $s ) . $s; $s; } for 1 .. length $s; return @r; }->( q{BANA$} );' ANB$A $

I think I read somewhere that chop is fast so it might be worth benchmarking.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Is it possible to make reference to substrings and sort them?
by AnomalousMonk (Archbishop) on Mar 22, 2015 at 19:19 UTC

    I thought of a similar approach, but as BrowserUk pointed out above, if a list of all rotations of a 5,000,000 character string must be generated and stored somewhere, it's going to crash and burn. Anyway, FWIW:

    c:\@Work\Perl\monks>perl -wMstrict -le "use Test::More 'no_plan'; ;; my $t = 'BANA$'; ;; my @rots = do { my $u = $t; map $u = chop($u) . $u, 1 .. length $u } ; ;; my $ar_expected = [ reverse qw(BANA$ ANA$B NA$BA A$BAN $BANA) ]; is_deeply \@rots, $ar_expected, 'cyclic rotations'; ;; my $bwt = join '', map chop, sort @rots ; ;; is $bwt, 'ANB$A', qq{'$t' -> '$bwt' transform}; " ok 1 - cyclic rotations ok 2 - 'BANA$' -> 'ANB$A' transform 1..2
    The generation of the  @rots array is broken out into a separate step just so it can be tested against the OPed data; normally, it would be part of the sort operation chain.


    Give a man a fish:  <%-(-(-(-<