| I'll throw my hat in the ring of other "xor" tricks. So we all know addition swap. One generalization that comes to mind is doing some other in-place transform on the two input variables. Lets keep it simple and suppose that its a linear transform. Thus the problem is to apply some matrix [[a,b],[c,d]] to two input variables [x,y] using entirely in-place operations. We can do this by realizing that our basic operands can be expressed as matrices.
x += ky is the same as the matrix
[1, k]
[0, 1] likewise y += kx is equiv to the lower triangular matrix
[1, 0]
[k, 1] and lastly, the = operator is equiv to a matrix with an element on the diag.
x = k
[k ,0]
[0, 1] y *= k
[1, 0]
[0, k] From this point on it becomes a challenge of if you can construct any desired matrix into some combination of these available ones (spoiler, yes you can). The next generalization one could contemplates is doing operations in place on more than 2 variables. Well, if one has already solved arbitrary 2x2 matrix operations, then that can be rigged to implement larger matrices one submatrix at a time. The final generalization that comes to mind is what can we do with non-arithmetic operators? We've already seen an example of this with using xor-swap rather than addition-swap. But is there anything out there vaguely like xor-2x2-matrix-multiply? I legit don't know. I have some thought, but I won't meander out loud if its not going to lead anywhere. |