Front page | perl.fwp | Postings from June 2006

## RE: SPUG: swapping two numbers

From:
DeRykus, Charles E
Date:
June 23, 2006 16:42
Subject:
RE: SPUG: swapping two numbers
Message ID:
FE10499CE029B841A9DAAF12E5A52A1B0296943A@XCH-NW-3V1.nw.nos.boeing.com

M> I was digging through some old code and came across a proof that I
M> that you can swap two numbers in place (i.e. without using an
external
M> temporary value).

M> Of course, in Perl, we can just do this:
M>  (\$x, \$y) = (\$y, \$x)

M> But I was challenged (at a GSLUG meeting) to do it in a
language-independent way.
M> Since the guy mentioned he had known the solution for 20+ years, I
descended into
M> bit-flipping land and came up with a solution.

M> (BTW:  I'm not sure why my first gut reaction was right.  I guess
I've been in the
M> business long enough.  There's no way my conscious mind came up with
this solution!!!
M> Nevertheless, my subconscious came up with this solution within about
3 seconds.
M> Brains are amazing!!!)

M> I present it here as an interesting piece of code:

M> #! /usr/bin/perl -w

M> use warnings;
M> use strict;

M> my \$iterations = shift @ARGV || 10;

M> for (my \$i = 0; \$i < \$iterations; \$i++) {
M>   my (\$orig_a, \$a) = (int(rand 1000)) x 2;
M>   my (\$orig_b, \$b) = (int(rand 1000)) x 2;

M>   # Original solution:
M>   #    \$a = \$a ^ \$b;
M>   #    \$b = \$b ^ \$a;
M>   #    \$a = \$a ^ \$b;
M>   # Refined to use op=
M>   #    \$a ^= \$b;
M>   #    \$b ^= \$a;
M>   #    \$a ^= \$b;

M>   # Utilizing op= value, factored onto one line
M>   #    \$a ^= (\$b ^= (\$a ^= \$b));
M>   # Refined to remove unnecessary parens
M>    \$a ^= \$b ^= \$a ^= \$b;

'Algorithms with Perl' has your original, refined solution in the
Crytography chapter (pg. 539 'Swapping values with XOR') but not
the nice, de-cluttering refinement.

--
Charles DeRykus

• RE: SPUG: swapping two numbers by DeRykus, Charles E

nntp.perl.org: Perl Programming lists via nntp and http.