Reputation: 11
I'm trying to figure out how to swap more than two variables around using a temp variable. There are 4 variables to be swapped, 1,2,3 and 4. Variable one is to swap with 2, 2 with 3, 3 with 4 and 4 with 1. It seems simple enough but I've only learnt how to swap two variables so and am struggling with the larger scale. I've tried
temp = 1
1 = 2
temp = 2
2 = 3
temp = 3
3 = 4
temp = 4
4 = 1
Do i need more than one temp variable? Still only a beginner any help would be appreciated!
Edit: Sorry, forgot to add I'm coding for java.
Upvotes: 1
Views: 4590
Reputation: 49372
An array is a better approach for your requirement . In your present pseudo code , you can do something like this :
temp = 1
1 = 2
2 = 3
3 = 4
4 = temp
In java , you can do something like below using array :
int[] x = {5,15,25,35};
int temporary = x[0];
for(int j=0;j<x.length-1;j++){
x[j]=x[j+1];
}
x[x.length-1]=temporary;
Upvotes: 1
Reputation: 22949
Consider what happens in the third step. The original value of 1
(which was saved to temp
in the first line) is lost, because you overwrite temp
with the value of 2
.
As it turns out, there is no need to save a copy of the original value of 2
because there is already a copy in 1
. The same applies to all the other variables (except 1
).
So the only time you need to use temp
is at the very start to save the value of 1
(like you are currently doing), and also at the very end when you assign the original value of 1
to 4
. You can't use 1
because it was overwritten, but a copy was saved in temp
just for this purpose.
So the final code looks like this:
temp = 1
1 = 2
2 = 3
3 = 4
4 = temp
Upvotes: 1
Reputation:
Just use an array along with a loop and one temporary variable will be enough. P-code since you didn't mention the language:
array = { 1, 2, 3, 4 }
tmp = array[0]
for i in [0, array.count - 1)
array[i] = array[i + 1]
array[array.count - 1] = tmp
Upvotes: 1