Advertisement
Guest User

Untitled

a guest
Jul 7th, 2010
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3.  
  4. public class ArrayElementShifter {
  5.  
  6.     private static boolean printDebug = true;
  7.    
  8.     private static int dimension = 10;
  9.    
  10.     private static int n = 3;
  11.    
  12.     /**
  13.      * @param args
  14.      */
  15.     public static void main(String[] args) {
  16.        
  17.         //array initialization
  18.         Integer[] initArray = new Integer[dimension];
  19.         for(int i=0; i<dimension; i++) initArray[i] = i+1;
  20.        
  21.         //Move N elements to the end and print results
  22.         System.out.println("\nResult: " + Arrays.toString(moveNElementsToTheEnd(initArray, n)));
  23.     }
  24.    
  25.     public static final Object[] moveNElementsToTheEnd(Object[] initArray, int n){
  26.        
  27.         //for index calculation simplicity natural numbers (1,2,3...) are used;
  28.         //for addressing array elements index-1 is used
  29.        
  30.         int freeCellIdx = 1, nextValueIdx = 0;
  31.         Object tmp = initArray[freeCellIdx -1];
  32.        
  33.         for(int i=0; i<initArray.length; i++){
  34.             nextValueIdx = (freeCellIdx + n > initArray.length ? freeCellIdx - initArray.length : freeCellIdx) + n;
  35.             initArray[freeCellIdx-1] = nextValueIdx == 1 ? tmp : initArray[nextValueIdx-1];
  36.             freeCellIdx = nextValueIdx;
  37.  
  38.             if(printDebug) {
  39.                 System.out.println("Debug:" + Arrays.toString(initArray));
  40.             }
  41.         }
  42.        
  43.         return initArray;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement