Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class ArrayElementShifter {
- private static boolean printDebug = true;
- private static int dimension = 10;
- private static int n = 3;
- /**
- * @param args
- */
- public static void main(String[] args) {
- //array initialization
- Integer[] initArray = new Integer[dimension];
- for(int i=0; i<dimension; i++) initArray[i] = i+1;
- //Move N elements to the end and print results
- System.out.println("\nResult: " + Arrays.toString(moveNElementsToTheEnd(initArray, n)));
- }
- public static final Object[] moveNElementsToTheEnd(Object[] initArray, int n){
- //for index calculation simplicity natural numbers (1,2,3...) are used;
- //for addressing array elements index-1 is used
- int freeCellIdx = 1, nextValueIdx = 0;
- Object tmp = initArray[freeCellIdx -1];
- for(int i=0; i<initArray.length; i++){
- nextValueIdx = (freeCellIdx + n > initArray.length ? freeCellIdx - initArray.length : freeCellIdx) + n;
- initArray[freeCellIdx-1] = nextValueIdx == 1 ? tmp : initArray[nextValueIdx-1];
- freeCellIdx = nextValueIdx;
- if(printDebug) {
- System.out.println("Debug:" + Arrays.toString(initArray));
- }
- }
- return initArray;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement