in reply to Merging Two Strings

If $s1 is equal with $s2, the merged region is $s1.

Your 2nd example follows this spec but your 3rd example doesn't. Either your spec and your 2nd example are wrong or your 3rd example is. I think that's the real source of the ambiguity everyone has been pointing out to you. If I had to guess, I'd say your 3rd example is wrong.

Assuming that's the case, I think the following will work:

sub merge { my ($s1, $s2) = @_; my $pos = length($s1) <= length($s2) ? 0 : length($s1) - length($s +2); $pos++ while substr($s1, $pos) ne substr($s2, 0, length($s1) - $po +s); substr($s1,$pos) = $s2; return $s1; }
It assumes that, in the event there is no overlap, the merged string is the concatenation of the two strings. (E.g. merge("ACTG","TCAG") eq "ACTGTCAG") It also assumes that the second string will never be contained in the first unless it is a tail substring. (E.g. merge("GATC", "AT") is "GATCAT" and not "GATC"   but   merge("GATC", "TC) is "GATC".)

Here's how it handles your examples:

$ merge.pl ATTTA TTTAA ATTTAA $ merge.pl ATGTA ATGTA ATGTA $ merge.pl ATGATG ATGATG ATGATG
Note in particular how it handles the your third example as it is different than the answer you provided.

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re^2: Merging Two Strings
by BrowserUk (Patriarch) on Oct 27, 2005 at 16:05 UTC

    Given the updated OP, a minor mod to my first attempt seems to work?

    P:\test>p1 perl> sub merge{ my( $s1, $s2 ) = @_; my $i= length $s1; $i-- until substr( $s1, -$i ) eq substr( $s2, 0, $i ); return $s1 . substr( $s2, $i ); };; perl> print merge( 'ATTTA', 'TTTAA' );; ATTTAA perl> print merge( 'ATGTA', 'ATGTA' );; ATGTA perl> print merge( 'ATGATG', 'ATGATG' );; ATGATG perl> print merge( 'ATGGTAC', 'CCGTAATG' );; ATGGTACCGTAATG

    But that still doesn't match the OPs solution to the 3rd example.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.