我有一個函數,binary_range_search
,被稱爲像這樣:如何延長二進制搜索迭代器消耗多目標
my $brs_iterator = binary_range_search(
target => $range, # eg. [1, 200]
search => $ranges # eg. [ {start => 1, end => 1000},
); # {start => 500, end => 1500} ]
brs_iterator->()
將遍歷上$範圍重疊的所有@ $範圍。
我謹向binary_range_search
能夠與多個範圍爲目標,例如把它稱爲:
target => $target_ranges # eg. [ [1, 200], [50, 300], ... ]
search => $search_ranges # as above
所以,當在$範圍內搜索 - > [0]耗盡時,它應該移至$ range - > [1],依此類推。這是有問題的功能,原來的形式:
sub binary_range_search {
my %options = @_;
my $range = $options{target} || return;
my $ranges = $options{search} || return;
my ($low, $high) = (0, @{$ranges} - 1);
while ($low <= $high) {
my $try = int(($low + $high)/2);
$low = $try + 1, next if $ranges->[$try]{end} < $range->[0];
$high = $try - 1, next if $ranges->[$try]{start} > $range->[1];
my ($down, $up) = ($try) x 2;
my %seen =();
my $brs_iterator = sub {
if ( $ranges->[ $up + 1 ]{end} >= $range->[0]
and $ranges->[ $up + 1 ]{start} <= $range->[1]
and !exists $seen{ $up + 1 })
{
$seen{ $up + 1 } = undef;
return $ranges->[ ++$up ];
}
elsif ($ranges->[ $down - 1 ]{end} >= $range->[0]
and $ranges->[ $down + 1 ]{start} <= $range->[1]
and !exists $seen{ $down - 1 }
and $down > 0)
{
$seen{ $down - 1 } = undef;
return $ranges->[ --$down ];
}
elsif (!exists $seen{$try}) {
$seen{$try} = undef;
return $ranges->[$try];
}
else {
return;
}
};
return $brs_iterator;
}
return sub { };
}
這是一個標準的二分法搜索策略,直到它找到一個重疊的範圍。然後它向右移動,耗盡它,向左移動,耗盡它,最後放棄。理想情況下,它應該可能是下一個目標範圍,然後重新搜索,我想(可能是通過遞歸?)。我的問題是,我不確定如何使用迭代器構建工作。
這幾乎是完美的;我從來沒有想過將迭代器推入堆棧。不過,這個函數返回的迭代器被用作累加器函數的輸入。當然,我可以改變累加器重用多個迭代器。謝謝!。 – 2010-01-12 21:28:59