Hi, all! Could someone please help me to solve such a task. I need to swap variable values without using any assignment signs. I tried to do it with a while loop but I coudn't store counter value anywhere. Thank you all in advance.
See Bit Twiddling Hacks it'll show you how to do it in a number of different ways without using assignments.
Since integers are immutable in C#, you cannot "Swap Integer variables without using any assignment"; you will need to reassign them somewhere, somehow. Perhaps you mean Swap two variables without using a temp variable?
Or, if you meant without explictly using =
, @Konrad Rudolph's answer is the way to go.
Xor-swap uses assignments. But perhaps you’re allowed to use increment and decrement (which, strictly speaking, resolve to += 1
and -= 1
in C# but logically they are often considered to be different).
int tmp = 0; // C# complains if we don’t initialize!
while (a-- > 0)
tmp++;
while (b-- > 0)
a++;
while (tmp-- > 0)
b++;
This is a logic sometimes used in the analysis of primitive calculi, such as the LOOP program formalism. Of course, these formalisms don’t require initialization of fields, otherwise the whole “no assignment” rule would be completely moot. In a strict calculus, tmp
would have to be zero-initialized by a loop, too:
while (tmp > 0)
tmp--;
This will work no matter what value tmp
had before (provided tmp > 0
, which is usually a requirement in all these calculi: negative numbers don’t exist).
But, to stress this once again, C# requires us to initialize each local variable (non-local variables are default-initialized) so this loop would be redundant in C#, and an initialization is still required.
As @Doc Brown pointed out in the comments, this only works for (positive!) integers – although theoretically (once again: not in C#!) this could be made to work with any type that can be represented on a Von Neumann architecture since they all reside in memory as numbers (to some base).
I don't think this is even possible in C#.
The XOR answer is the standard, but you can only grab hold of the memory and manipulate its values directly in lower-level languages.
.net languages will allow you to perform the equivalent of an XOR operation and return the value but to store it you still have to assign it, as far as I'm aware. You just don't have the direct memory access to perform the operation in this manner, as far as I can think...
class Program
{
private static void Swap(ref int a, ref int b)
{
int.TryParse((a ^ b).ToString(), out a);
int.TryParse((a ^ b).ToString(), out b);
int.TryParse((a ^ b).ToString(), out a);
}
static void Main(string[] args)
{
int a = 42;
int b = 123;
Console.WriteLine("a:{0}\nb:{1}", a, b);
Swap(ref a, ref b);
Console.WriteLine("a:{0}\nb:{1}", a, b);
}
}