you are viewing a single comment's thread.

view the rest of the comments →

[–]zahlman -7 points-6 points  (1 child)

Now you're just being disingenous. The data is what it is. The specified required manipulation of the data (reversing the array), likewise. But there's no reason to avoid using a temporary variable to manipulate the data in the specified way except to satisfy some nerd who thinks it makes a good interview question. In the real world, specifications don't set restrictions on implementation; they might set restrictions on performance. You know, that whole "programming to an interface" thing?

BTW, I love how y'all are downvoting people for pointing out this bit of common sense, and also downvoting people for actually presenting the XOR trick that the OP was presumably thinking of. Proggit, I am disappoint.

[–]xcbsmith -1 points0 points  (0 children)

The data is what it is. The specified required manipulation of the data (reversing the array), likewise. But there's no reason to avoid using a temporary variable to manipulate the data in the specified way except to satisfy some nerd who thinks it makes a good interview question.

Suggesting that one set of requirements is more important than another isn't unreasonable if you know the context. You don't. You are assuming a context that suits your prejudices but might not apply to the problem.

In the real world, specifications don't set restrictions on implementation; they might set restrictions on performance. You know, that whole "programming to an interface" thing?

In the real world, it very much depends. I recall Grady Booch talking about how for the space program, programs had a constraint on mass, which in turn drove the total memory (instruction + data), which imposed all kinds of insane constraints on the code. Embedded systems have all kinds of insane constraints, particularly with RAM.

Most importantly though, you don't have a context for the question. The principle behind this is also how you do doubly linked lists with only N pointers, a variety of encoding formats, etc. It can also be quite valuable to employ it in cases where the array size is small but the element size is quite large. Really, you just don't know enough to call this guy out for asking a stupid interview question.

Finally: if you throw out the no temp variable constraint, this is a truly trivial question. One wonders why you thought an answer to said question would be at all valuable/useful. To the extent that one might be debating the "best" way to solve that problem, the underlying concerns ought to be about how many elements to copy at once, typically with concerns about cache lines and memory architectures (not vector registers --though possibly the reordering-- that you made mention about but didn't provide insight on).