繁体   English   中英

如何将数组中的值向左移动 3

[英]How to shift values in an array to the left by 3

我试图将数组中的值向左移动 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]);

}
}

最简单的方法是使用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));
  }
}

下面的代码演示了如何旋转数组。

第一个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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM