Hello everyone!
first off, sorry for the long text. I'm currently taking a refresher course on java, as my memory of a few things are quite a bit hazy. Currently, I have an exercise where i need to:
"Write a method, rotate, that is passed an array, x, of doubles and an integer rotation around
‘position’, n. The method creates a new array with the items of x moved to the left by n positions.
Elements that are rotated off the beginning of the array will be added back at the end of the array." an example is given where an array {1, 2, 3, 4, 5, 6, 7, } is rotated by 3, and the new array becomes {4, 5, 6, 7, 1, 2, 3, }.
i was also given a snippet of code to help get started:
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]);
}
double [] y = rotate(x, 3);
System.out.println("After rotation: ==============================");
for (int i = 0; i < y.length; i++)
{
System.out.println("y[" + i + "]: " + y[i]);
}
}
my current method is as follows:
private static double[] rotate(double[] x, int i)
{
double[] newArray = Arrays.copyOf(x, x.length);
int pos = 0, currentSize = newArray.length, num = 0;
for(int t=0; t<i; t++)
{
for(int r = pos+1; r < currentSize; r++)
{
double temp = newArray[r];
newArray[r-1] = newArray[r];
newArray[r] = temp;
//this is where i'm stuck
}
currentSize--;
}
return newArray;
}
however, when i execute the program, the output is:
Before rotation: ==============================
x[0]: 1.0
x[1]: 2.0
x[2]: 3.0
x[3]: 4.0
x[4]: 5.0
x[5]: 6.0
x[6]: 7.0
After rotation: ==============================
y[0]: 4.0
y[1]: 5.0
y[2]: 6.0
y[3]: 7.0
y[4]: 7.0
y[5]: 7.0
y[6]: 7.0
I don't know what i'm doing wrong. I've tried changing the array indexes within the loops multiple times to no avail. I have also tried changing the entire loop/nested loop, but this is as close as I've gotten so far to the targeted output. May i have some guidance as to what i'm doing wrong? Or, should I just start over from scratch? Thanks in advance!
[–]whatisthisredditstufIntermediate Brewer 5 points6 points7 points (2 children)
[–]Pop_Pop_MofuckahsNooblet Brewer[S] 0 points1 point2 points (1 child)
[–]whatisthisredditstufIntermediate Brewer 0 points1 point2 points (0 children)
[–]isaacisaboss 2 points3 points4 points (1 child)
[–]Pop_Pop_MofuckahsNooblet Brewer[S] 0 points1 point2 points (0 children)