Re: mini-golf: first differing position

"Craig S. Cottingham" <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <1082512129.1156.93.camel@scorpio>
On Tue, 2004-04-20 at 19:26, Bernie Cosell wrote:
> On 20 Apr 2004 at 19:57, [email protected] wrote:
> > We want to find out the first position $n at which strings $x and $y
> > differ.  If $x eq $y, then $n is undef.  If $x ne $y but $x is a
> > prefix (aka initial segment) of $y, then $n should be equal to length
> > $x.  The operation must preserve both $x and $y (i.e. destructive
> > operations are disallowed).
> 
> How about [not golfing so the code is clearer]:
>     my $diff = $x ^ $y;
>     my ($len) = $diff =~ /^([\0])[^\0]/ ;
>     return uhdef if not defined $len ;
>     return length $len;'

I couldn't get that to work. However, it *did* give me an idea:

sub mydiff {
    my($a,$b)=@_;
    my($len)=unpack('B*',unpack('B*',$a)^unpack('B*',$b))=~/^((0{8})+)/;
    $a eq $b?undef:int(length($len)/64);
}
my $diff = &mydiff(@ARGV);
print defined($diff)?$diff:'undef'."\n";

> perl mydiff.pl A A
undef
> perl mydiff.pl A B
0
> perl mydiff.pl AA AA
undef
> perl mydiff.pl AA AB
1
> perl mydiff.pl AA AAB
2

I don't fully grok pack/unpack, especially 'B' fields, so I'm sure it
can be improved on.

-- 
Craig S. Cottingham
[email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.