Reputation: 21
so I'm trying to shift an array to the right so that x will appear as 4, 5, 6, 7, 1, 2, 3. I think my algorithm is correct but for some reason it won't return x and just skips anything after the "x = rotate(x, 3)" line. Any help or explanation would be appreciated.
public class Ex1sub3 {
public static void main(String[] args){
double[] x = {1, 2, 3, 4, 5, 6, 7};
System.out.println("Before rotation: ==============================");
for (int i = 0; i < x.length; i++)
{
System.out.println("x[" + i + "]: " + x[i]);
}
x = rotate(x, 3);
System.out.println("After rotation:==============================");
for (int i = 0; i < x.length; i++)
{
System.out.println("x[" + i + "]: " + x[i]);
}
}
private static double[] rotate(double[] x, int n){
int l = x.length;
double [] r = x;
int c = 0;
int rotation;
int startRotation = 0;
for (c = 0; c < l; c++)
{
rotation = c+n;
while (rotation < l-n)
{
x[c] = r[rotation];
}
if (rotation >= l-n)
{
x[c] = r[startRotation];
startRotation++;
}
}
return x;
}
}
Upvotes: 1
Views: 1006
Reputation: 34
Your program does not skip any lines but will stuck in your rotate(...)
function. I can see no way to leave the inner while
loop since all variables in the condition are untouched in the body. But as @Peter Lawrey already mentioned: a debugger might prove useful in cases where the program flow is mysterious.
Upvotes: 0
Reputation: 533530
This is where a debugger would help you see but, the one problem is you are overwriting the value you first value to copy to without keeping it. e.g.
Say you have two elements, { 1, 2 }
The first thing you do is copy x[1] = x[0]
do the array is { 1, 1 }
i.e. you over wrote a value you can't get latter. Instead you need to hold the value to be copied. e.g.
double d = x[1];
x[1] = x[0];
x[0] = d;
This is more complicated when you shift by n
but it can be done. A simpler solution is to take a copy of the array before you rotate.
Upvotes: 1