few problems, approaches and solutions

subtleties of programming

While coding for the problem-2.3-7 , some how I was not in my default mode of not thinking while coding. To test my programs I was writing a random array generator. One part of it was to swap two array entries. Now, the most straight forward way to swap two array elements is

int tmp = arr[i];
arr[i]  = arr[r];
arr[r]  = tmp;

But, knowing the xor method, I thought why not save a variable. Basically, if a and b are to be swapped, then the code suffices.

a ^= b;
b ^= a;
a ^= b;

So now the question is, would this work on an array. Ex.

arr[i] ^= arr[r];
arr[r] ^= arr[i];
arr[i] ^= arr[r];

Here’s a subtle bug. If i and r are same, then it wont. The reason being that we loose the original value. If both indexes are same, the same array entry would be xor’ed with itself. Wiki page explains it better, and why it should be avoided in desktop systems. Again, I learn the evils of premature optimization. Subtleties of programming!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: