how to match two sequences using arrays in perl -
when looping through 2 arrays, confused how move pointer through 1 loop keep constant in another. example:
- array 1:
a t c g t c g g c g
- array 2:
a c g t c c t g t c g
so in first array matches in second array move on next elements. since t doesn't match c in 2nd index, want program compare t next g in array 2 , on until finds matching t.
my ($array1ref, $array2ref) = @_; @array1 = @$array1ref; @array2= @$array2ref; $count = 0; foreach $element (@array1) { foreach $element2 (@array2) { if ($element eq $element2) { $count++; }else { ??????????? }
you use while
loop search matches. if find match, advance in both arrays. if don't, advance second array. @ end print remaining unmatched characters first array:
# [1, 2, 3] reference anonymous array (1, 2, 3) # qw(1, 2, 3) shorthand quoted-word ('1', '2', '3') $arr1 = [qw(a t c g t c g g c g)]; $arr2 = [qw(a c g t c c t g t c g)]; $idx1 = 0; $idx2 = 0; # find matched characters # @$arr_ref size of array referenced $arr_ref while ($idx1 < @$arr1 && $idx2 < @$arr2) { $char1 = $arr1->[$idx1]; $char2 = $arr2->[$idx2]; if ($char1 eq $char2) { # matched character, advance arr1 , arr2 printf("%s %s -- arr1[%d] matches arr2[%d]\n", $char1, $char2, $idx1, $idx2); ++$idx1; ++$idx2; } else { # unmatched character, advance arr2 printf(". %s -- skipping arr2[%d]\n", $char2, $idx2); ++$idx2; } } # remaining unmatched characters while ($idx1 < @$arr1) { $char1 = $arr1->[$idx1]; printf("%s . -- arr1[%d] beyond end of arr2\n", $char1, $idx1); $idx1++; }
the script prints:
a -- arr1[0] matches arr2[0] . c -- skipping arr2[1] . g -- skipping arr2[2] t t -- arr1[1] matches arr2[3] c c -- arr1[2] matches arr2[4] . c -- skipping arr2[5] . t -- skipping arr2[6] g g -- arr1[3] matches arr2[7] t t -- arr1[4] matches arr2[8] c c -- arr1[5] matches arr2[9] g g -- arr1[6] matches arr2[10] . -- arr1[7] beyond end of arr2 g . -- arr1[8] beyond end of arr2 c . -- arr1[9] beyond end of arr2 g . -- arr1[10] beyond end of arr2
Comments
Post a Comment