gpt4 book ai didi

perl - 如何在perl中使用数组匹配两个序列

转载 作者:行者123 更新时间:2023-12-05 01:08:56 26 4
gpt4 key购买 nike

当循环遍历两个数组时,我对如何在一个循环中移动指针但在另一个循环中保持不变感到困惑。例如:

  • 数组 1:A T C G T C G A G C G
  • 数组 2:A C G T C C T G T C G

  • 所以第一个数组中的 A 与第二个数组中的 A 匹配,所以我们继续下一个元素。但是由于 T 与第二个索引中的 C 不匹配,我希望程序将该 T 与数组 2 中的下一个 G 进行比较,依此类推,直到找到匹配的 T。
    my ($array1ref, $array2ref) = @_;

    my @array1 = @$array1ref;
    my @array2= @$array2ref;
    my $count = 0;
    foreach my $element (@array1) {
    foreach my $element2 (@array2) {
    if ($element eq $element2) {
    $count++;
    }else { ???????????


    }

    最佳答案

    您可以使用 while循环搜索匹配项。如果找到匹配项,则在两个数组中前进。如果不这样做,请推进第二个阵列。最后,您可以打印第一个数组中剩余的不匹配字符:

    # [1, 2, 3] is a reference to an anonymous array (1, 2, 3)
    # qw(1, 2, 3) is shorthand quoted-word for ('1', '2', '3')
    my $arr1 = [qw(A T C G T C G A G C G)];
    my $arr2 = [qw(A C G T C C T G T C G)];

    my $idx1 = 0;
    my $idx2 = 0;

    # Find matched characters
    # @$arr_ref is the size of the array referenced by $arr_ref
    while ($idx1 < @$arr1 && $idx2 < @$arr2) {
    my $char1 = $arr1->[$idx1];
    my $char2 = $arr2->[$idx2];
    if ($char1 eq $char2) {
    # Matched character, advance arr1 and 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) {
    my $char1 = $arr1->[$idx1];
    printf("%s . -- arr1[%d] is beyond the end of arr2\n", $char1, $idx1);
    $idx1++;
    }

    脚本打印:
    A 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]
    A . -- arr1[7] is beyond the end of arr2
    G . -- arr1[8] is beyond the end of arr2
    C . -- arr1[9] is beyond the end of arr2
    G . -- arr1[10] is beyond the end of arr2

    关于perl - 如何在perl中使用数组匹配两个序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16346304/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com