0

I have two variables M & N and with certain condition in my loop I want to switch the value of N between itself and M. So the following code came in my mind

MxN = M * N;

N = MxN/N;

But values of M and N may be 2 000 000 000. Therefore Im in doubt. Is that fine variant to switch between such a huge values or may be its better(faster) to

counter = 2;
N = counter % 2 == 0 ? M : N; 
counter++;

edit Sorry I didn't mention that I dont want to affect the value of M
Thanks everyone)

4
  • You can't do "temp = M; M = N; N=temp;"? Am I misunderstanding your question? Commented Mar 8, 2013 at 15:05
  • not to switch M with N but to switch N between N and M Commented Mar 8, 2013 at 15:07
  • @SakerONE Could you please add an example of input->output to your question? Commented Mar 8, 2013 at 15:09
  • input M = 3; N = 5; at first iteration of the loop N - 3 at second N - 5 at third N - 3 and so on Commented Mar 8, 2013 at 15:11

3 Answers 3

2

There are so many ways.

1 http://jsfiddle.net/8NvVf/

m -= n
n += m
m = n - m

2 http://jsfiddle.net/eQGwL/ (Only works in FireFox and maybe Rhino)

[n, m] = [m, n]

3 http://jsfiddle.net/4MQXe/

m = (n += m -= n) - m

Edit

If you don't want to change the value of m you need a temp value.

http://jsfiddle.net/Yjkn3/

var n = 5
var m = 8
var t = n

for (var i = 0; i < 10; ++i) {
    if(n != m) n = m
    else n = t
    console.log(n + ' ' + m)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, I didn't know that it was also to do such swap trick using arrays in Javascript. Is that a new language feature or something that existed "since the beginning"?
Sorry I didn't mention that I dont want to affect the value of M
1

Both approaches are suspect to an integer overflow (and the earlier one also to precision errors). Why not limit the range of the counter and adapt the second approach?

state = 0;
switch (state) {
case 0:
    // ...
    break;
case 1:
    // ...
    break;
// ...
}

state = state < maxState ? state + 1 : 0;

It is up to you to optimize this, but please keep readability and maintainability in mind. An alternative to this switch is to use an array.

For two variables, please do not mess with xor hacks when trying to swap variables, just write what you want:

var temp = N;
N = M;
M = N;

Comments

0

The classic trick for swapping two values is to use XOR:

x = x xor y
y = x xor y
x = x xor y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.