3 ms·
This is similar to how to swap two numbers without using temporary variable: X = 31; Y = 25; console.log(X, Y); // prints 31 25 X = X + Y;
by dvh 5y ago
This is similar to how to swap two numbers without using temporary variable:
X = 31;
Y = 25;
console.log(X, Y); // prints 31 25
X = X + Y;
Y = X - Y;
X = X - Y;
console.log(X, Y); // prints 25 31
- teddyh 5y agoOnly if you assume that X+Y never exceeds 9007199254740991 (Number.MAX_SAFE_INTEGER, 2⁵³-1). Also, that algorithm has nothing in common with the image rotation one; the image rotation algorithm does require a temporary buffer.
- nomel 5y agoThis is why I like python: X = 31 Y = 25 X, Y = Y, X
- robomartin 5y agoThis still creates a temporary variable. Sorry.
- brrrrrm 5y agoWhere? Variables are a language semantic not an implementation detail. A temporary variable is just a new symbolic name. You may be thinking of temporary storage
- robomartin 5y agoSemantics. You still have to use additional resources for the swap. BTW, in Python, "a,b = b,a" is actually faster (execution time) than explicitly using a third variable. In other words, I am not saying it is a bad technique, just saying it has to use additional resources for the swap, that's all. In fact, the Python idiom is faster even if you doing something like: a,b = b[:],a[:]
- nomel 5y ago> Semantics I would claim it's not semantics. Variables are meant for humans, not computers. Variable does not necessarily mean storage. If you're outside of interpreted languages, the code you type is very often not the code that is executed. If this were a compiled language, there's no way to know if temporary storage was used or not, without looking at the generated machine code. There's a very real chance that something as useless as swapping variables would be optimized away completely.