+ 2

Hi, who can help me to solve this

var a=x; var b =y; when write alert(a) it will be y, and alert(b) to be x: without use any functions, cicle, if, other var

18th Oct 2018, 9:46 AM
Vahe Davtyan
Vahe Davtyan - avatar
14 Respuestas
+ 5
So you want to swap two variables without using a third one? Hint: if we do a += b, then a is x+y and b is y. What can we do now to turn b into x? 😉 The rest is similar.
18th Oct 2018, 12:41 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
1) [a,b]=[b,a]; 2) b = [a, a = b][0]; 3) b^=a^=b, a^=b;
18th Oct 2018, 1:23 PM
Микола Федосєєв
Микола Федосєєв - avatar
+ 1
thank you
18th Oct 2018, 12:48 PM
Vahe Davtyan
Vahe Davtyan - avatar
+ 1
You're welcome. Were you able to solve it? Let me know if what I said sounds confusing :)
18th Oct 2018, 12:52 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
ok, if i need ask you, i will
18th Oct 2018, 12:54 PM
Vahe Davtyan
Vahe Davtyan - avatar
+ 1
a += b; // now a is x+y, b is y b = a - b; // now a is x+y, b is x a -= b; // now a is y, b is x Done! Does that makes sense?
18th Oct 2018, 1:32 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
Kishalaya Saha, if x can be used, the swapping process is significantly easier: a=b; b=x; The task is not to use anything except a and b
18th Oct 2018, 4:52 PM
Микола Федосєєв
Микола Федосєєв - avatar
+ 1
Микола Федосєєв Thanks, I was careless. Fixed.
18th Oct 2018, 5:05 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
a=x b=y // swap using math a-=b // a=x-y b+=a // b=x a=b-a // a=y // swap using xor a^=b // a=x^y b^=a // b=y^(x^y)=x a^=b // a=(x^y)^x=y
18th Oct 2018, 5:06 PM
Микола Федосєєв
Микола Федосєєв - avatar
+ 1
Yes, I'm aware of the bitwise XOR swap. But I don't think it's easier to understand than the add-subtract method.
18th Oct 2018, 5:20 PM
Kishalaya Saha
Kishalaya Saha - avatar
0
i try to do it just now, thank you once more
18th Oct 2018, 1:08 PM
Vahe Davtyan
Vahe Davtyan - avatar
0
Friend i can't solve this, i am beginner and i don't know what to do. Help
18th Oct 2018, 1:20 PM
Vahe Davtyan
Vahe Davtyan - avatar
0
thank you friend, but i dont understand, i am beginner, i need very simillar answer
18th Oct 2018, 1:27 PM
Vahe Davtyan
Vahe Davtyan - avatar
0
Let's reader decide what's better. If he/she is not familiar with xor, at least the fact of such possibility should be put into brains. Understanding will come later. Add-substract may be not too easy for big numbers with it's overflow problem, while xor is absolutely clean.
18th Oct 2018, 5:45 PM
Микола Федосєєв
Микола Федосєєв - avatar