Javaing
Javaing

Reputation: 47

Shift elements circularly in array by n

I am trying to shift the elements of an array left by n (some random number) using a method. The difficulty is with swapping the elements at the start of the array with the elements at the end. Here is my code so far.

The other array questions asked were different from this one.

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();
    }
}

Upvotes: 2

Views: 1626

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234797

Since you apparently don't need to do the shift in place and can use a temporary array, the solution is pretty simple:

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();
    }
}

This only works for calls to shift with argument values that are legal subscripts of datas. If you want to handle negative values or values greater than datas.length, you'll need to reduce position to the appropriate range. Note that since this is a circular shift, you can use modular arithmetic to advantage here, since shift(position) and shift(position * n*datas.length) should yield the same result for any integer value n.

Upvotes: 1

Will
Will

Reputation: 20235

You could make good use of the modulo operation for this.

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;
}

Upvotes: 6

Related Questions