SPUG: scalar swap challenge [semi-SPOILER]

Yitzchak Scott-Thoennes sthoenna at efn.org
Wed Oct 8 15:50:07 CDT 2003


On Wed, Oct 08, 2003 at 01:04:42PM -0700, "Michael R. Wolf" <MichaelRWolf at att.net> wrote:
> 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");
> }

Just a comment on the test script:

Because perl will silently shift from integers to floating point where
necessary, such swap code may have a flaw that this test won't
exercise, at least where NVs don't preserve all the bits of an IV.
Just increasing the 1000 to 2**63 won't help, since I think that a
single int(rand()) sequence will end up only producing integers that
are representable in floating point.

I don't think this problem is solvable in perl without some limitation
on what kind of integers are input.

(This kind of problem is why you should try to have perl use long
doubles when using long longs.  Unfortunately, many platforms have
adequate support for one but not the other.)



More information about the spug-list mailing list