in reply to interchanging variables the tough way
I end up swapping $a with $b, then $b with $c, (2 2-way swaps) not very original. I'm pretty sure that I (or someone else) could come up with a shorter piece of code that does the same thing, by taking advantage of the fact that it is a 3-way swap.$a=$a ^ $b; $b=$a ^ $b; $a=$a ^ $b; $b=$b ^ $c; $c=$b ^ $c; $b=$b ^ $c;
One cool thing is because of how perl implements xor on scalars is that this works for "strings" in addition to working for "numbers". Still won't work for refrences or undef though :(.
UPDATE
I've done some experiments and managed to find 90 diffrent ways of doing the xor 3-way swap with 6 xor operations. I wasn't able to find any with fewer than 6 xor operations. The only "advantage" is that some of the new ones I discovered are harder to read/follow. Example:
$b=$b^$c; $a=$a^$c; $c=$a^$c; $a=$a^$b; $a=$a^$c; $b=$a^$b;
|
---|