This is a little practice task for those who have already mastered programming and want to try their hand at solving more difficult problems.
Let's imagine that you're writing the code for a keyless entry device (commonly called a key fob) which will be used for apartment security. Key fobs have very limited memory, so each byte should be cherished. Your task is to swap the numeric values in two variables:
- For example, variable a stores the number 3, and variable b stores the number 5.
- You need to make it so that a stores 5, and b stores 3.
How can we do this if only these two variables can be used? We can't create a temporary third variable as that would occupy extra memory.
Solution
A beginning programmer might come up with something like this:
a = b;
b = a;
We can immediately spot the error — as soon as we write a = b, we lose the value of the variable a. The fact is, after such an assignment, the value of b will be stored in both variables, and the value of a will no longer be available. Let's run the code in the browser and check it out:
The proof is in the pudding, or rather, the console. It's clear that the value of variable a has been lost and now we have two identical values of b.
Our task is to store both a and b somewhere at the same time so that we can assign their values to the necessary variables. Let's see if the following approach works with just two variables.
Let's assign the sum of a and b to the variable a:
a = a + b; // now a stores the sum of both, and b still stores its original value
Now it's time for a trick. We'll assign the initial value of a to b. It's easy to get this value because we'll just subtract b from the sum that is now stored in a:
b = a − b; // b now has the initial value of a, which we got by subtracting b from the sum
We've still got to restore the initial value of b. Since we now have the sum, and the value of a, we can simply subtract it from the sum:
a = a - b; // the initial value of b has appeared in a, we got it from the sum
Let's check our code in the browser:
Hopefully, this task got your mental gears turning and got you ready for your next challenge. Until then, we have one more tiny puzzle for you to chew on. Try to achieve the same result without using addition and subtraction. Remember, there's not a lot of memory in that little key fob so you won't be able to use any other variables. Good luck!
And after mastering this task, why not take your swapping skills into the real world, too? Swap the new you for the old you! Bid adieu to the old you, and get ready to greet the leveled-up version of yourself, working in your dream career. At Practicum by Yandex, we offer online education and mentorship to help you develop a career in tech. You'll tackle even more practical challenges and build a portfolio of projects you can show off to your future employers. Plus, you'll do it all while working in an awesome and supportive environment with both peers and mentors.