Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
swapping variables
#21
Cheat? Cheat on what rules?
The terms of the problem/riddle are: swap two variables without using extra storage.
The XOR algorithm solves the riddle.
Where's the cheating?
Reply
#22
It's not cheating though, it's just practical maths.

a += b
b = a - b
a -= b

a *= b
b = a / b
a /= b

a ^= b
b ^= a
a ^= b

Hell, even taking the integral and the derivative works with this method, just way less efficient.
Reply
#23
Orit Wrote:What? You don't need to split anything. In C, you'd code something like:

Code:
char *p,*q;
for (p=a, q=b; *p != '\0' && *q != '\0'; p++, q++)
{
  *p ^= *q;
  *q ^= *p;
  *p ^= *q;
}
/* add the tail of the (previously) longer string onto the shorter.
    This assumes there was enough room for it there.
    If there wasn't, we shouldn't be attempting to swap anyway,
    as new memory would need to be allocated.
*/
if ((*p == '\0') && (*q != '\0'))
{
  strcpy(q,p);
  *q = '\0';
}
else if ((*p != '\0') && (*q == '\0')
{
  strcpy(p,q);
  *p = '\0';
}

Obviously this is not very human-readable. It's only one step removed from assembly language.

When I need to swap strings, I would just swap the address of the pointers instead of swapping the array itself.

if *p points to the first string and *q points to the 2nd string, swap p and q around and they're effectively the same as swapping values irrespective of the size of the string.

BTW, xor is exclusive OR, ie either this or that, but not both and not none.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)