Sunday, June 17, 2018

Swap Two Integers without using a Temporary Variable

This is an older exercise, but it still comes up.
This falls under things you wouldn't bother worrying about in real life.

Swap Two Integers without using a Temporary Variable

The idea is to just add the two integer variables and then subtract each piece out in turn.

Say you have x=5 and y=9.

If you are using Python you can just stop right here as "tuple unpacking" will so all the work for you.

x, y = (y, x)

and you are done. x is 9 and y is 5.

Let's assume you want to do it the harder way...

Replace x with the sum of x and y.

x = x + y

x = 5 + 9 = 14

Now you have "lost" x, but you still have y and you can deduce what your old x is.

For the new y take your total and subtract out y, which will leave you with the "old" x in y's place.

y = x - y

y = 14 - 9 = 5

Now to get the new x, take the total and subtract out the new y. which will give you the old y which goes in x's place.  It's more confusing to write it out in English that to just see the math.

x = x - y

x = 14 - 5 = 9

To Summarize

x = x + y   [x changes]
y = x - y    [y changes: Total minus original y]
x = x - y    [x changes again]


Eva E. Murphy said...

I used to believe that swapping without using a temporary variable was impossible, but your posts have convinced me it is possible. seriously, your blogs are too good, they always provide me something unique. I wish I could visit more of your blogs, but I am not able to do that right now because I have to find a platform from which I can Buy Compare And Contrast Essay online at an affordable price.

Dissertation Writing Services London said...

Goodness Algebra! That was a tough subject. Back in my school days, I had a friend that helped me with my algebra class. She works in one of the popular Dissertation Writing Services London now and we do not talk a lot anymore. In school, we used to talk and play often but I lost touch with her ever since we entered universities. Maybe I should contact her again. Anyways thank you for bringing back so many memories.