Java Array Shift shift(T[] array, int count)

Here you can find the source of shift(T[] array, int count)

Description

shift all elements of an array

License

Apache License

Parameter

Parameter Description
T the type of the elements
array the array to shift
count the count of steps to shift. Use a positive value for right shift and a negative for shift to left

Return

a new array with the shifted elements

Declaration

public static <T> T[] shift(T[] array, int count) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.Arrays;

public class Main {
    /**// ww  w  . j  a v  a 2s .  c om
     * shift all elements of an array
     * 
     * @since 0.0.1
     * 
     * @param <T> the type of the elements
     * @param array the array to shift
     * @param count the count of steps to shift. Use a positive value for right
     *            shift and a negative for shift to left
     * @return a new array with the shifted elements
     */
    public static <T> T[] shift(T[] array, int count) {
        int length = array.length;
        T[] res = Arrays.copyOf(array, length);

        if (count == 0) {
            return res;
        }

        for (int i = 0; i < length; i++) {
            int srcIdx = i - count;

            while (srcIdx < 0) {
                srcIdx += length;
            }
            while (srcIdx > (length - 1)) {
                srcIdx -= length;
            }

            res[i] = array[srcIdx];
        }

        return res;
    }
}

Related

  1. shift(String[] array)
  2. shift(String[] in)
  3. shift(String[] original, int offset)
  4. shift(String[] src, String word)
  5. shift(String[] tokens)
  6. shiftArgs(final String[] args)
  7. shiftArgs(String[] args, int offset)
  8. shiftArray(String[] args, int shift)
  9. shiftArray(String[] array, int offset)