In practice I cannot think of a time when I was confronted with this particular problem. Usually if I need to find a duplicate I have no guarantees that there isn’t more than one or if there is a duplicate at all. I don’t think I’ve ever had to practically solve the “every number but one” problem. Curious where such problems arise in the wild, except interview puzzles.
That XOR Trick (2020)
11–20 of 243 posts
Re: That XOR Trick (2020)
#12There are in fact legit use cases for XOR to speed things up or make algorithms simpler, but this is not the case here IMHO.
Re: That XOR Trick (2020)
#13The xor swap can be dangerous: if variables have the same value, they xor to zero so you end up losing the values of both variables.
Re: That XOR Trick (2020)
#14The xor swap can be dangerous: if variables have the same value, they xor to zero so you end up losing the values of both variables.
x=2, y=2:
x^=y => x=0, y=2
y^=x => x=0, y=2
x^=y => x=2, y=2
Re: That XOR Trick (2020)
#15Re: That XOR Trick (2020)
#16Re: That XOR Trick (2020)
#17> XOR all values between 1 and n An O(n) algorithm!? You'd expect there to be a closed-form solution for this, analogous to summing a series using n*(n-1)/2. OEIS to the rescue. http://oeis.org/A077140 gives ((n+1)%2)*n + (n+(n%2))//2 % 2
Re: That XOR Trick (2020)
#18The xor swap can be dangerous: if variables have the same value, they xor to zero so you end up losing the values of both variables.
You where saying?
Re: That XOR Trick (2020)
#19As mentioned in this article, x ^ x == 0. Fun fact, this is frequently used by compilers as a "cheap" way to zero out a register. In addition, there are comparatively few cases in programming where we XOR. Sure, it happens in things like games quite a lot, but the main use is actually _cryptography_. Between these two facts (more like hints really), I managed to reverse engineer the bulk of a piece of malware I was g…
Re: That XOR Trick (2020)
#20As mentioned in this article, x ^ x == 0. Fun fact, this is frequently used by compilers as a "cheap" way to zero out a register. In addition, there are comparatively few cases in programming where we XOR. Sure, it happens in things like games quite a lot, but the main use is actually _cryptography_. Between these two facts (more like hints really), I managed to reverse engineer the bulk of a piece of malware I was g…
For example, XOR is the most convenient combining function for Zobrist hashes in chess programs. OR/AND would be bad choices: given random input, their output is biased to the values 1 and 0 (respectively).