Home > c#, General > Random Thought Experiment – Swapping Variables

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.

Advertisement
Categories: c#, General
  1. Mana
    May 29, 2009 at 12:22 am | #1

    Instead of 3, you’re using four variables. They are initialized when you call the function: it’s just another method of declaring them.

  1. No trackbacks yet.

Leave a Reply

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

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

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

Facebook photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.