On Thu Sep 04 14:29:42 2008, KWILLIAMS wrote:
Show quoted text> It would be nice if there were an Interval_Norm() method that would
> compute the number of
> bits set within a range:
>
> $norm = $vec->Interval_Norm($from, $to);
>
> Currently it seems the available solutions are sub-optimal, requiring
> allocation of additional
> bit vectors and examining too much of $vec:
>
> $mask = $vec->Shadow;
> $mask->Interval_Fill($from, $to);
>
> $temp = $mask->Shadow;
> $temp->And( $vec, $mask );
>
> $norm = $masked->Norm;
>
> Of course if there's a better solution I'm overlooking, I'd love to
> hear it.
There is at least a shorter solution:
$temp = $vec->Clone();
$temp->Interval_Empty(0,$from-1) unless ($from-1 < 0);
$temp->Interval_Empty($to+1,$temp->Size()-1) unless ($to+1 >
$temp->Size()-1);
$norm = $temp->Norm();
Show quoted text> It would also be nice if there were a simple Interval() method that
> would just return a sub-
> vector:
>
> $sub = $vec->Interval($from, $to);
>
> That would make several operations on sub-vectors more convenient. I
> believe the current
> solution is to do:
>
> $sub = Bit::Vector->new($to-$from+1);
> $sub->Interval_Copy($vec, 0, $from, $to-$from+1);
>
> Which works fine but is a bit wordy (if you'll pardon the pun).
>
> -Ken
There is also a different solution:
$sub = Bit::Vector->new($to-$from+1); # any size is ok here, but correct
size should be a trifle faster
$sub->Interval_Substitute($vec,0,$sub->Size(),$from,$to-$from+1);
Note that "Interval_Substitute" is the same for bit vectors as what
"splice" is for Perl arrays.
This alternate solution is not easier to read in this example, but might
be more helpful in other circumstances than the use of "Interval_Copy".
And yes, Bit::Vector is somewhat "wordy" - but hey, it's a module for
low-level functions in the first place!
By the way, you can always write a very short little method yourself
which does it (put at the top of your program):
package Bit::Vector;
sub Interval
{
my($self,$from,$to) = @_;
# You should add some parameter checking here of course!
my $sub = Bit::Vector->new($to-$from+1);
$sub->Interval_Copy($vec, 0, $from, $to-$from+1);
return $sub;
}
package WhateverYouLike;
# Your program goes here
And you're done! :-)
Same goes of course for the "Interval_Norm" method you mentioned above.
Hope this helps.