citromatik has asked for the wisdom of the Perl Monks concerning the following question:
Hi all
In a recent post, someone asked how to find if two numeric ranges overlap. I couldn't resist to try a solution based on bit vectors. That is, create 2 bit vectors with the bits inside the range set to "1", and see if the & operation on them give something different to a vector of '0's. Something like:
use strict; use warnings; my ($bv1,$bv2,$bv3) = ('') x 3; vec ($bv1,$_,1)=1 for (11..19) # First range vec ($bv2,$_,1)=1 for (15..25) # Second range vec ($bv3,19,1)=0 # The "0" vector -- should have + the length of the shorter. print unpack ("b*",$bv1),"\n"; print unpack ("b*",$bv2),"\n"; print unpack ("b*",$bv3),"\n",'-'x60,"\n"; my $olap = $bv1 & $bv2; print unpack ("b*",$olap),"\n\n"; print +(($bv1 & $bv2) eq $bv3 ? "don't overlap\n" : "overlap\n");
This works as expected:
1 000000000001111111110000 2 00000000000000011111111111000000 0s 000000000000000000000000 ------------------------------------------------------------ & 000000000000000111110000
but I find a bit tricky to have to build the '0' vector for comparisons and the fact that the bit vectors 000 and 0000000000000000 are not equals
Is there a better way to see if a bit vector has all its bits set to '0'?
Thanks in advance
citromatik
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: comparing bit vectors
by BrowserUk (Patriarch) on Jun 11, 2009 at 10:15 UTC | |
|
Re: comparing bit vectors
by almut (Canon) on Jun 11, 2009 at 10:52 UTC |