A Quick and Tricky Programming Exercise
This is to test how well master variable assignment in programming
One day, my father asked to do a quick programming exercise.
Swap two integer variables without introducing a third variable.
Zhimin: My interest in programming started in high school. At that time, I was selected for the state’s youth programming competitions. (I did win one 3rd prize and one 2nd prize. Many years later, I received the 2nd prize of the 2018 Ruby International Programming Award in Japan).
I can still recall a fun & tricky programming exercise that our coach put forth.
We all know how swapping works in code:
a = 1
b = 2
c = a
a = b
b = c# a => 2; b => 1
Simple, many programmers remember this with “caabbc
”, where c
is the temporary variable. Now, accomplish the swapping task without this temporary variable.
Some reader’s (like me) first reaction might be, “That’s not possible”.
Tip: There is a feasible solution that works for all languages, with no tricks.
I sat down and worked out the solution quite quickly.
Here, I show a video of automated test execution in TestWise (a testing IDE I created), which is nothing related to this programming task, rather, just a space holder to avoid spoiling the answer.
The solution:
a = a + b
b = a - b
a = a - b
Some readers might complain, “This only works for two integers”, true. It was specified clearly in the task (also with examples).
This really tests a programmer’s understanding of ‘variable assignment”, while beginners often read (and understand) the code a = 3
as “a equals 3”, the correct one is “integer 3 is assigned to variable a”.
Of course, in real coding, you should never write the code like that, as it is not intuitive, hard to maintain.
Speaking of intuitiveness, The Ruby language tops that for this operation.
a, b = b, a
Related reading:
- My ebook: Learn Ruby Programming by Examples
My interactive course: Discover Ruby Programming Through Fun Examples