in reply to Intersecting Two Strings

It seems to me that no searching is required, as all the relevant information already present in the input data.

A grossly over elaborate coding is:

#! perl -slw use strict; my $s1 = "1,0,CTGCCACCGCTGT"; my $s2 = "1,5,ACCGCTGTGTTTCGGCCGGCGA"; my @s1 = split ',', $s1; my @s2 = split ',', $s2; if( $s1[0] == $s2[0] ) { if( $s1[1] > $s2[1] ) { my @temp = @s1; @s1 = @s2; @s2 = @temp; } if( $s2[1] < length( $s1 ) ) { ## Updated to correct the error pointed out by Lima1++ below my $l1 = length( $s1[2] ) - $s1[1] - $s2[1]; my $l2 = length( $s2[2] ); $l1 = $l2 if $l2 < $l1; print "The intersection between the strings:\n", $s1[2], "\n", ' ' x ( $s2[1] - $s1[1] ), $s2[2], "\nis\n", ' ' x $s2[1], substr $s1[2], $s2[1] - $s1[1], $l1; ; print "\nand it occurs at a 1-based offset into the sequence o +f ", $s2[1] + 1; } else { print "The strings do not intersect"; } } else { print 'Strings are not from the same sequence'; } __END__ c:\test>junk The intersection between the strings: CTGCCACCGCTGT ACCGCTGTGTTTCGGCCGGCGA is ACCGCTGT and it occurs at a 1-based offset into the sequence of 6

The bits you are probably interested in are

  1. The bit to extract the overlap:
    substr $s1[2], $s2[ 1 ] - $s1[ 1 ], length( $s1[2] ) - $s1[1] - $s2[1] +;
  2. And the bit to calculate the 1-based offset:
    $s2[1] + 1;

but they won't work correctly unless you split the input strings into their constituant parts and ensure that the first is the 'lesser' of the two.

It could undoubtedly be golfed some.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: Intersecting Two Strings
by lima1 (Curate) on Aug 23, 2007 at 11:18 UTC
    You forgot one corner case:
    my $s1 = "1,0,CTGCCACCGCTGT"; my $s2 = "1,5,ACCG";
    Apart from that, our solutions are identical-but your code is nicer I must admit ;)
      You forgot one corner case:

      I did, didn't I :(

      I apologise for missing that you'd seen the same anomaly as I, amongst all the LCS posts.

      but your code is nicer I must admit ;)

      Actually, I think yours perfectly fine. Missing a couple of steps and tests, but fine. More importantly it works.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.