Wednesday, January 5, 2011

Tattoo Beautiful Agony

Scambio di due variabili senza la variabile di appoggio

The classic method for the exchange of two variables, with denotiamole b, involves the use of a third variable support, call it c, and consists essentially in carrying out assignments in the following sequence:

c =
to a = b = c b

In this topic, will be shown an alternative method that will make the exchange without the use of the third variable support c.
The idea of \u200b\u200bthis method for numerical variables can be attributed to my good friend John Valentino and was then subsequently extended to the case alphanumeric from me. In what follows, therefore, distinguish i due casi analizzandoli separatamente.

Caso numerico
Dette a e b le variabili numeriche da scambiare, possiamo effettuare lo scambio effettuando in successione le seguenti operazioni:

a = a + b
b = a - b
a = a - b

Come si potrĂ  verificare, tale metodo funziona correttamente per qualsiasi valore numerico che si attribuisce alle variabili a e b.
Passiamo quindi ad esaminare il caso alfanumerico.

Caso alfanumerico
Per esaminare tale caso, al fine di aumentare the clarity and understanding in practical terms it, we will refer to the syntax of a specific programming language, although the procedure can be applied using any other language.
As mentioned, the syntax is that of the Java language.
The steps, follow in the footsteps of the case number and differ from this only in some details.
More specifically, these b alphanumeric variables to be exchanged, the operations to be performed are as follows:


a = a + b;

/ / a.substring b = (0, 0 + a.length () - B.length ()); equivalent to:
a.substring b = (0, a.length () - b.length ());

/ / a = a.substring (b.length (), b.length () + a.length () - b.length ()); equivalent to:
/ / a = a.substring (b.length (), a.length ()); equivalent to :
a.substring a = (b.length ());


Again, you can easily see that the method works for any string attached to the variables a and b.

conclude this topic, noting that: Although the method described optimizes the use of memory space, it as the flip side, the increase in computational time due to operations that must be performed.
In short, the above method is equivalent to the traditional and the choice of either depends entirely on the type of optimization you want: more space and less time in the case of traditional, less space and more time for the method described. Obviously, however, since these optimizations really minimal, especially given the power obtained from the current computers, the choice of method, in fact, depends on factors related solely to personal taste.

0 comments:

Post a Comment