Swap two variables using XOR – BetterExplained
It almost seems like magic – the the same statement is repeated 3 times and voila – the values magically swap? Let’s take a closer look. To understand this trick, break the statements into unique values: According to our code, x2 should have y’s original value. Let’s work out the details for the last step: Wow – x2 really does equal y! The swap happened. Now let’s try it out for y1: And tada the trick worked again. x2 and y1 have the swapped answers. Ok, sure, the boolean algebra works out great — but that’s not satisfying. I want to understand it deep down and have it make sense, not be some artifact of the properties of XOR. Let’s take another look: On line 1 we combine x and y (using XOR) to get this “hybrid” and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again. So, this is exactly what we do on line 2. We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into
Most people would swap two variables x and y using a temporary variable, like this: tmp = x x = y y = tmp Here’s a neat programming trick to swap two values without needing a temp: x = x xor y y = x xor y x = x xor y Don’t believe me? Try it out – write in any initial value for x and y: It almost seems like magic – the the same statement is repeated 3 times and voila – the values magically swap? Let’s take a closer look. How it works To understand this trick, break the statements into unique values: x1 = x xor y y1 = x1 xor y x2 = x1 xor y1 According to our code, x2 should have y’s original va
saved by
related reading
- Home - The XY Problemxyproblem.info
- Get better at programming by learning how things workjvns.ca
- Basic Bit Manipulation - HackMDhackmd.io
- A Gentle Introduction to Yao's Garbled Circuitsweb.mit.edu
- How the quantum search algorithm worksquantum.country
- X explains Z% of the variance in Y — LessWronglesswrong.com
- What is the simplest way to swap each pair of adjoining chars in a string with Python? - Stack Overflowstackoverflow.com
- Variables and Mutability - The Rust Programming Languagedoc.rust-lang.org
- Exchangeable random variables - Wikipediaen.wikipedia.org
- Branchless Equivalents of Simple Functions | Harder, Better, Faster, Strongerhbfs.wordpress.com
- Y: The Most Beautiful Idea in Computer Science explained in JavaScriptlucasfcosta.com
- Fantastic Learning Resourcesmatklad.github.io