[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [Fun With Perl] Re: How to swap $p and $q without $tmp



Bek Oberin <gossamer@tertius.net.au> writes:

> Roland Giersig wrote:
> > Easy. Just right to left. Equivalent multiline version:
> >  $q ^= $p;
> >  $p ^= $q;
> >  $q ^= $p;
> 
> I must be dumb.   I still don't get it.  Maybe its just too
> late at night?
> 

$oldp = $p;
$oldq = $q;
$q ^= $p;           # $q == $oldq ^ $oldp
$p ^= $q;           # $p == $oldp ^ $q == $oldp ^ $oldq ^ $oldp == $oldq
$q ^= $p;           # $q == $q ^ $p = $oldq ^ $oldp ^ $oldq == $oldp

All you need to know is that ^ is associative ((a^b)^c == a^(b^c)),
commutative (a^b == b^a), and that a^a == 0.

-- 
Ariel Scolnicov        |"GCAAGAATTGAACTGTAG"            |ariels@compugen.co.il
Compugen Ltd.          |Tel: +972-2-6795059 (Jerusalem)	\  NEW IMPROVED URL!
72 Pinhas Rosen St.    |Tel: +972-3-7658520 (Main office)`--------------------
Tel-Aviv 69512, ISRAEL |Fax: +972-3-7658555  http://3w.compugen.co.il/~ariels

==== Want to unsubscribe from this list? (Don't you love us anymore?)
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org