1
I recently made a very simple challenge :
Swap the value of two variables without using a third variable.
int a = 5;
int b = 3;
a += b; // a = 8
b = a - b; // b = 5;
a -= b; // a = 3;
It is simple because they are arithmetic operations.
Yet I was thinking how to do it if they were strings.
string a = 'Stack';
string b = 'Overflow';
I even thought of some solutions, but these apply to weak typing languages :
Example JS
var a = 'Stack';
var b = 'Overflow';
a = a+'|'+b; // a = 'Stack|Overflow';
a = a.split('|'); // a = ['Stack', 'Overflow'];
b = a[0]; // b = 'Stack';
a = a[1]; // a = 'Overflow';
How could I solve this challenge with string?
You have some restraint of what you can do?
– Maniero
@bigown no, just can’t use another variable.
– Guilherme Lautert
So I don’t care, these things don’t lead anywhere :P Doing it in a worse way when you can do it the best way I don’t like. The existing answer is sufficient.
– Maniero
@bigown The true test (with
ints
) had a mathematical purpose, so it made a certain sense :P– Jéf Bueno
@jbueno exactly, although I think it would be better done with bit operator. This is a crazy thing to do. It is quite slow and destructive of memory :)
– Maniero
@bigown I’m not a great connoisseur of C#, I even thought of some more methods by converting to binary, but then one would have to change the type of variable. I know you are a great connoisseur, I would like your participation, for learning purposes.
– Guilherme Lautert
You have nothing to do with this restriction. You may have a better solution than this, but none will be good. The obvious and good solution is to use a temporary variable. Unlike an integer that is small in size and the full copy does not generate large overhead,
string
generates different values. So you’re not creating a new variable, but is creating new values, which is much worse. If there was a reason to do this I would understand, but artificial restraint makes it a curiosity without practical sense.– Maniero
I understood, in case I would be using more memory than to do with a helper.
– Guilherme Lautert