2015-12-05 28 views
0

我正在尝试使用方法将数组中的元素左移n(某些随机数)。难点在于将数组起始处的元素与末尾的元素交换。这是我的代码到目前为止。在n数组中循环移位元素n

其他阵列问题与此不同。

public class Shifty { 

    private int[] datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; 

    public Shifty() { 
     datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; 
    } 

    public int shift(int position) { 
     int tmp = 0; 
     int[] tmp1 = new int[12]; 
     for (int i = 0; i <= 12; i++) { 
      if (i < position) { 

        tmp1[12-position] = this.datas[i]; 

      } else { 
       this.datas[i] = this.datas[i+1]; 
          } 
      for (int j = 12-position; j <= 12; j++){ 
       this.datas[j] = tmp1[j]; 
      } 
     } 

     return position; 
    } 

    public void display() { 
     System.out.println(Arrays.toString(this.datas)); 
     System.out.println(); 
    } 
} 
+0

例如看到这个:http://stackoverflow.com/questions/18659792/circular-arraylist-extending-arra- sylist和http://stackoverflow.com/questions/7266042/java-ring-buffer –

+0

你的'tmp1'太小 - 应该是int [13],但int [datqs.length]会更稳健。在你的代码中使用'12'也是一样。 – Jan

+0

哦,不好意思打错了。糟糕的手机键盘。 – Jan

回答

1

你可以很好地利用模运算。

public void shift(int n) { 
    int[] temp = new int[datas.length]; 
    for (int i = 0; i < temp.length; i++) { 
    temp[i] = datas[(i + n) % temp.length]; 
    } 
    datas = temp; 
} 
0

既然你显然不要做到位的转变,可以使用临时数组,该解决方案是非常简单的:

public class Shifty { 

    private int[] datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; 

    public Shifty() { 
     datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; 
    } 

    public int shift(int position) { 
     final int len = datas.length; 
     int[] tmp = Arrays.copyOf(datas, position); 
     System.arraycopy(datas, position, datas, 0, len - position); 
     System.arraycopy(tmp, 0, datas, len - position, position); 
     return position; 
    } 

    public void display() { 
     System.out.println(Arrays.toString(this.datas)); 
     System.out.println(); 
    } 
} 

这只适用于调用具有参数值转移这些是datas的合法下标。如果要处理负值或大于datas.length的值,则需要将position减少到适当的范围。请注意,由于这是一个循环移位,所以在这里可以使用模块化算术,因为shift(position)shift(position * n*datas.length)应该对任何整数值n产生相同的结果。