in reply to Re^5: How do I reverse the order of the first and last word of a string?
in thread How do I reverse the order of the first and last word of a string?
I suspect the bit you find interesting is the "swap without temporary" - an old assembly language trick.
Hehe, actually I'm very fond of this technique because I... "invented it!" Well, to be fair it was during my first exposure to some programming language, in high school: it was an experimental course and the language was Turbo Pascal. (Not that I remember any significative Pascal any more, I was 13 back then, I guess.) The teacher asked us to write some code to swap two variables as an exercise and in turn I asked whether we should do so with a third variable, because to me it seemed so obvious that it was not worth asking at all. She answered: "do whatever you want". So I "decided" that the requirement couldn't be the ridiculously simple solution with a temporary variable and worked my mind around one that wouldn't use it. The variables were integers and my solution was (in pseudo code):
a = a - b b = a - b (a-2b) a = a - b (a-b-a+2b=b) b = b + 2a (a-2b+2b=a)
(In parentheses the full expressions in terms of the initial values of a and b.)
This is actually the same trick as the XOR one, since it only relies on ring properties and XOR is both a minus and a plus in Z_2. Of course in that case the last step is not required because in the field Z_2, 2x=0 for all x.
Needless to say, the teacher did expect the temporary variable trick and pointed out that mine, despite how proud of it I were, would only work with numerical data, which is true. All in all she wasn't very happy. Nor was I: if only she had confirmed that she wanted a third variable in the first place...
</anecdote>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: How do I reverse the order of the first and last word of a string?
by jeanluca (Deacon) on Mar 11, 2007 at 11:36 UTC | |
by blazar (Canon) on Mar 11, 2007 at 12:14 UTC |