Wednesday, October 17, 2007

No Temps!

Puzzle -
Switch the values of two variables without using a third temporary variable.
Sample Input -
var A = 5
var B = 10

Sample Output -
var A = 10
var B = 5

7 comments:

Josh Schramm said...

Somehow I don't think this is what you're going for but...

A *= 2
B /= 2

Kevin Berridge said...

I like Josh's answer the best.

However, I saw this on a website awhile back discussing Fizzbuzz. I knew it had something to do with xor, but I've never been able to remember what xor actually does, so I cheated and looked it up.

Here's the answer:
x = x ^ y
y = x ^ y
x = x ^ y

Nathan Grant said...

In ruby you can do

A, B = B, A

but i suppose that's a little like cheating, too. :)

Benjamin P Lee said...

Josh, your answer rocks.

Kevin, you got it (assuming ^ is the XOR operator). I figured it was a fitting start. :)

Unknown said...

Man, I completely over-generalized that problem.

Anonymous said...

Question 1: I don't know what language josh's expression is in. Can you explain it to me? I don't understand what operations it is doing.

Question 2: I guess that the XOR does a bit by bit XOR? That is an amazing and simple property of operation sequences there, I've never seen that. I suppose that the ^ operator is commutative, i.e. x^y is the same as y^x?

Question 3: It seems that all these work by storing an arithmetic combination of the two into one of them. Then by doing inverse operations, get an expression into the other variable that is a different combination of the original two. Then exploit the arithmetic relationship in whatever way necessary to eliminate the original variables from their original locations, leaving the residual other variable. Not as elegant as yours, but to make the point:
If you only had add/subtract:
x=x+y
y=y-x
x=x+y
y=0-y
And if you only had mult/div:
x=xy
y=x/y
x=x/y

question 4: what about the "hey your shoelace is untied!" method.
echo off
temp=x
x=y
y=temp
echo on
print "abra cadabra"

Benjamin P Lee said...

To answer your questions:
1)
A *= B is equivelant to A = A * B.

I am not 100% sure, but I believe all of the languages that are syntactically based on C have this short-hand notation available.

2) yes, he was refering to the XOR operation which is a bitwise operation. And yes, XOR is commutative (e.g. 1101 XOR 0101 = 1000 and 0101 XOR 1101 = 1000)

3) i agree, my only concern with doing it that way is that you "may" run into overflow errors and/or precision errors with the mathematical operations. the beauty of the XOR operation in this context is that you are garaunteed that everything fits in your original buffer sizes.

4)genius

... "What is the best way to get an A on a test?" .... "CHEAT!"