SPUG: scalar swap challenge

John W. Krahn krahnj at acm.org
Wed Oct 8 15:35:44 CDT 2003


On Wednesday 08 October 2003 13:04, Michael R. Wolf wrote:
>
> swap challenge> In most languages, values cannot be directly swapped
> without a swap challenge> temporary variable. It's a classic problem
> shared by passing trains, swap challenge> elevator passengers, and
> virtual memory systems. swap challenge>
> swap challenge> A swap code fragment typically looks like this.
> swap challenge>
> swap challenge>     $temp = $left;
> swap challenge>     $right = $left;
> swap challenge>     $left = $temp;
> swap challenge>
> swap challenge> Perl's list assignment can do this directly.
> swap challenge>
> swap challenge>     ($left, $right) = ($right, $left);
> swap challenge>
> swap challenge> Recently, I got challenged to do a swap without a
> temporary variable swap challenge> in C by someone who claimed it's
> always possible. Actually, it's swap challenge> always possible for
> *integral* types. Because I no longer enjoy coding swap challenge> in
> C, I reworded it to be a Perl challenge:
> swap challenge>
> swap challenge>    swap two integral scalars without using a
> temporary scalar and swap challenge>    without using the list
> assignment swapping idiom.

It is pretty easy in perl:

$ perl -le'
my ( $x, $y ) = ( 32, 765 );
print "$x    $y";
$x ^= $y; $y ^= $x; $x ^= $y;
print "$x    $y";
( $x, $y ) = qw( six seven );
print "$x    $y";
$x ^= $y; $y ^= $x; $x ^= $y;
print "$x    $y";
'
32    765
765    32
six    seven
seven    six


:-)

John
-- 
use Perl;
program
fulfillment



More information about the spug-list mailing list