Random Thought Experiment – Swapping Variables
Recently I was reading a post about using a fizzbuzz test to find developers that grok coding. Some of the comments also talked about using a simple swap test (i.e. swap the values of these two variables) and how this could be done without resorting to the use of a third variable.
While I can appreciate the”geek factor” or XORing variables together such that you can swap their values without requiring the use of a third, I would not want to use this approach anywhere except where memory was extremely limted, it is horribly unclear what is happening to someone that does not know about or understand the approach. This set me to thinking, how could you swap to variables around in a reasonably clear manner without resorting to the use of a third. The following is what I came up with.
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
namespace Swap
{
public class Swap
{
public static void DoSwap(int a, int b, out int swappedA, out int swappedB)
{
swappedA = b;
swappedB = a;
}
}
[TestFixture]
public class SwapTest
{
[Test]
public void DoSwap_Should_Swap_A_And_B()
{
int a = 3;
int b = 5;
Swap.DoSwap( a, b, out a, out b );
Assert.That( a, Is.EqualTo( 5 ) );
Assert.That( b, Is.EqualTo( 3 ) );
}
}
}
Simple, effective, completely pointless and fun to solve.
Instead of 3, you’re using four variables. They are initialized when you call the function: it’s just another method of declaring them.