Saturday, January 7, 2012

Circular Swap

Given three numbers a, b and c. Write a program to swap them circularly (as per following example) using only one single statement in any programming language.

Ex. a=10 b=20 c=30

Answer a=20 b=30 c=10

Solution :
a = a^b^c^(b=c)^(c=a);
This is equivalent to a = (a^b^c^c^a) = b along with the values of b and c being changed by b=c and c=a assignments.
This is an excellent answer and defeats the proposed ones in the reference.
Reference :
http://stackoverflow.com/questions/8635686/swap-three-numbers-in-single-statement