加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

循环遍历两个数组,删除perl中的重叠

发布时间:2020-12-16 06:25:02 所属栏目:大数据 来源:网络整理
导读:我有两组范围,由[start,stop]值表示.一些范围重叠,这意味着一个范围的开始位于另一个范围的[开始,停止]之间.我想制作一组没有这种重叠的新范围,并且不包括范围内的任何新值. 范围看起来像这样: @starts @ends 5 108 5 187 44 187 44 229 44 236 64 236 104
我有两组范围,由[start,stop]值表示.一些范围重叠,这意味着一个范围的开始位于另一个范围的[开始,停止]之间.我想制作一组没有这种重叠的新范围,并且不包括范围内的任何新值.

范围看起来像这样:

@starts  @ends
      5    108 
      5    187
     44    187
     44    229 
     44    236 
     64    236 
    104    236
    580    644
    632    770

我期望的输出是这样的:

@starts  @ends
      5    236
    580    770

这是因为前七个范围与从5 =>的间隔重叠. 236和最后两个重叠,间隔从632 => 770.

这是我试过的代码:

$fix = 0;
foreach (@ends) {  
    if ($starts[$fix + 1] < $ends[$fix]) {
        splice(@ends,$fix,$fix);
        splice(@starts,$fix + 1,$fix + 1);
    } else {
        $fix += 1;
    }
}

我可以自己打印出这些值,我只需要帮助合并算法.

解决方法

这会就地编辑您的数组,只是在重叠时折叠边界.

# Since they're sorted by @starts,accept the 0th interval,start at 1
for (1..$#starts) {
    # extra check on array bounds,since we edit in-place
    last unless $_ < @starts;
    # don't need to collapse if no overlap with previous end
    next unless $starts[$_] <= $ends[$_-1];
    # delete this start and the previous end
    splice(@starts,$_,1);
    splice(@ends,$_-1,1);
    # rerun this loop for the same value of $_ since it was deleted
    redo;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读