Need help on array rotation

Oct 2, 2011 at 11:40am
Im new here and I would like some help on my program.

My program involves a 10x10 array. I have to rotate only the first row of the array once. The succeeding rows don't have to be modified.

ie.
4 3 2 1 1 2 3 4 2 1
1 2 2 2 1 1 2 2 1 2
3 4 3 4 4 4 3 3 4 4
... etc

into
1 4 3 2 1 1 2 3 4 2
1 2 2 2 1 1 2 2 1 2
3 4 3 4 4 4 3 3 4 4
... etc

I have already written a code for it. (I'll only put that part of the program down)

int rotate(){
int c;
int j;
c = array[1][9];
for(j=9; j<0; j--){
array[1][j] = array[1][j-1];
array[1][0] = c;

}
}
where c is the temporary variable.

when I ran the program, nothing has changed. Basically, I printed the array before and after this module and they were both the same.

Any insights?


Oct 2, 2011 at 3:07pm
closed account (D80DSL3A)
for(j=9; j<0; j--). j<0 is false right away.
Try for(j=9; j>0; j--).
Also array[1][0] = c; doesn't need to be in the loop. Assigning it once after the loop is enough.
Oct 3, 2011 at 10:14am
There seems to be another problem though.

4 3 2 1 1 2 3 4 2 1

becomes

4 4 3 2 1 1 2 3 4 2

The digit to the right vanishes and the first digit is doubled. Can anyone see a pro
blem with the code?
Oct 3, 2011 at 10:20am
can you show your new code?
Oct 3, 2011 at 10:25am
int rotate(int r){
int c;
int j;
while(r>0){
for(j=9; j>0; j--){
array[0][j] = array[0][j-1];
}
r--;
}
}

The variable "r" is for iteration. It seems to be working fine.
Last edited on Oct 3, 2011 at 10:26am
Oct 3, 2011 at 11:50am
Because it has to cycle through the row, there's always going to be one value that gets overwritten before it gets copied. Either used a temp variable to store it and then copy it to its destination at the end, or do the following:

1
2
3
4
5
#include <algorithm>

for (int i = last; i > 1; --i) {
  swap(array[0][i], array[0][i-1]);
}

It will iteratively push the last element one step forward until it is the first element. There is no risk over "overwriting", because no value is copied. Instead, values are "moved".

(Behind the scene, values of course ARE copied, but that doesn't really matter. As far as the programmer is concerned, values are moved, not copied.)
Oct 3, 2011 at 11:54am
@Gaminic:
How should the temp variable be positioned? The one I tried in my opening post does not work I'm afraid. Also, I don't think we're allowed to use swap since it was not taught in class.
Oct 3, 2011 at 11:58am
Put your "temp restore" (can't pinpoint the line because you didn't use code tags, but I mean the line where you reassign the value of 'c' to an array element) outside of the for loop. It should only copy the value after the rest is done.
Oct 3, 2011 at 12:10pm
Omg. Thought I've already tried that before but failed. Thanks for the help man =D
Oct 3, 2011 at 12:21pm
No problem!

Just don't forget to tag your topic as "fixed" if your code works, and to use code tags in your next topic!
Topic archived. No new replies allowed.