Swapping two variable values without using a third value

I have been cautiously dipping my toe into the Odin Project, an open-source online resource for learning to code. One of the downsides of the project is that it specifically tells you not to get lured down rabbit-holes, before linking to several supplementary articles. These link to others, of course, and then… well, in my case I ended up reading about programmers who can’t program.

Apparently it is not unusual to have candidates with no programming skills apply to programming jobs. The article suggests some screening tests to weed out these optimists. I would fail most of these tests. This is unsurprising, as I don’t consider myself a programmer, despite an amateur interest and some past experience with fairly basic Python, R, and PHP scripts. However, in the comments there was one screening problem that was described as:

swap two variables without using a third variable

This piqued my interest, because it seemed pretty easy. I was intrigued that one comment said:

“We hired the guy who said, well, “if they’re integers, then I’d do it by a=a|b, b=a^b, a=a^b. But I don’t know how to do it if they’re strings.”

I then found a whole plethora of answers on StackOverflow about how to do this in C++, none of which looked especially simple.

So I fired up R Studio Cloud and tried the following:

a <- b <- c(a,b)
a <- a[2]
b <- b[1]

Is this an acceptable solution? It works for and a and b of the same datatype, including integers or strings. Although a vector is created, this is not stored in a third variable. I would have thought this approach could be recreated in most languages. It works identically in Python, for example:

a = b = [a,b]
a = a[1]
b = b[0]

Leave a Comment

Your email address will not be published.