Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hello monks,
i have two sequences (strings)
the strings of numbers like
$a = 1,2,3,6,7,9,1,-7,2,6
$b = 7,6,7,9,12,-22,-3
i need to align string $a with respect to string $b
the output should be like this
the aligned sequence is 6,7,9
Thanks

Replies are listed 'Best First'.
Re: how can i align two two strings
by mwah (Hermit) on Dec 09, 2007 at 20:12 UTC

    The problem *can* be translated into a LCSS thing, just by reformatting the numbers into a hexdump of appropriate size:

    Addendum: added display of alingnment positions pa/pb

    ... use String::LCSS_XS qw(lcss); my $str_a = join '', map sprintf("%08x", $_), 1,2,3,6,7,9,1,-7,2,6; my $str_b = join '', map sprintf("%08x", $_), 7,6,7,9,12,-22,-3; # - - - - - - - - - - - - - - - - - - - # my @longest = lcss( $str_a, $str_b ); # - - - - - - - - - - - - - - - - - - - # print join ',', map hex, $longest[0] =~ /.{8}/g; my ($pa, $pb) = map 1+$_/8, @longest[1,2]; print "\na's pos # $pa alingns to b's pos # $pb\n"; ...

    This will show:

    6,7,9 a's pos # 4 'aligns' to b's pos # 2

    ... but its hard to say without knowing what you are really trying to do. This might be very very inefficient and rather suboptimal.

    Regards

    mwa

Re: how can i align two two strings
by CountZero (Bishop) on Dec 09, 2007 at 20:46 UTC
    Although it looks suspiciously like home-work, it is also Sunday evening and I am feeling generous.
    use strict; use Algorithm::LCSS qw( LCSS ); use Data::Dump qw /dump/; my @first_sequence = (1,2,3,6,7,9,1,-7,2,6); my @second_sequence = (7,6,7,9,12,-22,-3); my $lcss_ary_ref = LCSS( \@first_sequence, \@second_sequence ); {local $" = ','; print "The aligned sequence is @$lcss_ary_ref\n";}

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      generosity killed the cat (false buddha)
        #!/usr/bin/perl use strict; use warnings; use Data::Dumper; use List::Compare; my $a = '1,2,3,6,7,9,1,-7,2,6'; my $b = '7,6,7,9,12,-22,-3'; my @a = split ',', $a; my @b = split ',', $b; my $lc = List::Compare->new( \@a, \@b ); my @intersection = $lc->get_intersection; print Dumper(@intersection);
        output :
        $VAR1 = '6'; $VAR2 = '7'; $VAR3 = '9';
        voilą ;)
        PooLPi
Re: how can i align two two strings
by moritz (Cardinal) on Dec 09, 2007 at 19:51 UTC