我正在尝试将数组中的值向左移动3。我要说明的是使整个代码向左旋转。
double[] x = {38, 44, 15, 11, 27, 19, 8, 12, 10};
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-3; i++)
{
System.out.println("x[" + i + "]: " + x[i]);
}
}
答案 0 :(得分:0)
最简单的方法是使用System.arraycopy
:
public class Answer {
public static void main(String[] args) {
double[] initial = {8, 4, 5, 21, 7, 9, 18, 2, 100};
double[] shifted = new double[initial.length];
System.arraycopy(initial, 3, shifted, 0, initial.length - 3);
System.out.println(Arrays.toString(shifted));
}
}
答案 1 :(得分:0)
下面的代码演示了如何旋转数组。
第一次arraycopy()
调用将复制数组的后半部分(从rotateBy
到末尾)。第二次arraycopy()
调用复制了数组的开始部分(从开始到rotateBy
)。
import java.util.Arrays;
public class Rotate {
public static void main(String[] args) {
double[] input = {8, 4, 5, 21, 7, 9, 18, 2, 100};
double[] output = rotate(input, 3);
System.out.println("Input: " + Arrays.toString(input));
System.out.println("Output: " + Arrays.toString(output));
}
public static double[] rotate(double[] inputArray, int rotateBy) {
double[] output = new double[inputArray.length];
System.arraycopy(inputArray, rotateBy, output, 0, inputArray.length - rotateBy);
System.arraycopy(inputArray, 0, output, inputArray.length - rotateBy, rotateBy);
return output;
}
}