SPUG: scalar swap challenge

Michael R. Wolf MichaelRWolf at att.net
Wed Oct 8 15:04:42 CDT 2003


I sent the following to MJD for use as a possible QOTW, then decided
to share it wit SPUG first.

Enjoy,
Michael

If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.
If you post an answer, please put "SPOILER" in the subject line.


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.

Here's a little test script I put together to test my solution *after*
I'd proven it on paper.

#! /usr/bin/perl -w

use warnings;
use strict;

my $iterations = shift @ARGV || 10;

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

    # Your $a/$b swap code goes here.
    $a = "something";
    $b = "something";

    printf("%4d %4d %s\n" =>
	   $a, $b,
	   $a == $orig_b && $b == $orig_a ? "passed" : "failed: a was $orig_a, b was $orig_b");
}


-- 
Michael R. Wolf
    All mammals learn by playing!
        MichaelRWolf at att.net




More information about the spug-list mailing list