Wednesday 29 May 2019

The Good Old Variable Swap

A very elementary exercise in programming entails variable swapping. That's when a and b are variables with values, and you use computer logic to swap their values. Most programming classes teach the use of a temporary variable, like so. I'm just going to write this in QBasic as an example. In this case, the value of a is 3 and the value of b is 2.

DIM a = 3
DIM b = 2
DIM c

c = a
a = b
b = c


In the example above, c is used as a variable to temporarily house the value of a, while a assumes the value of b. To complete the process, b takes on the value of c (which held the old value of a) and presto - a is now 2 and b is now 3.

Swapping glasses of water.

This is often illustrated using two glasses of water. If you wanted to swap the water in one glass with the water in the other glass, how would you do it? You can't just swap it straight away - you would need a third glass (or container) to facilitate the transfer.

Now for the tough bit...

How do you swap the values of two variables without using a third variable?

There's no practical use for this, by the way. But it's sometimes asked as a brainteaser, or to test a programmer's logical skills. So try this. First, we assign the variables. Again, the value of a is 3 and the value of b is 2.
DIM a = 3
DIM b = 2


Now, we add a and b together and assign the value to a. a is now 5.
DIM a = 3
DIM b = 2

a = a + b


Next, we know the combined value of a and b is 5, and is now the value of a. We also know the current value of b, which is 2. So the old value of a must be 5 - 2 = 3. Thus, we assign that value to b.
DIM a = 3
DIM b = 2

a = a + b
b = a - b


Since b is now 3, which is the old value of a, then the old value of b has to be 5 - 3 = 2. We assign that value to a.
DIM a = 3
DIM b = 2

a = a + b
b = a - b
a = a - b


And the variables are swapped! The analogy of the glasses of water isn't applicable here anymore. Interesting, eh?

There are other ways, of course. Let's examine another one.

Using the XOR operator...
DIM a = 3
DIM b = 2

a = a ^ b
b = b ^ a

a = a ^ a
b = b ^ b


This works too, and it's arguably more elegant than the first example. However, I prefer the first example because it's presented in layperson logic. Primary school arithmetic. It reinforces my belief that you don't have to be a rocket scientist to learn programming. Of course, these work only if the values are numeric.

In Python, you could do this, and it would work regardless of what data types a and b are. But I dunno, that just seems to defeat the entire purpose of the exercise.
a, b = b, a

That's all. Glass dismissed!
T___T

No comments:

Post a Comment