fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. /* Name of the class has to be "Main" only if the class is public. */
  6. class Ideone
  7. {
  8. public static void main (String[] args) throws java.lang.Exception
  9. {
  10.  
  11. // Main array to be accessed from innermost to outermost element
  12. int[] arr = new int[]{1,2,3,4,5};
  13. int[] map = creatIndexMap(arr.length);
  14. printOut(arr, map);
  15.  
  16. int[] arr2 = new int[]{1,2,3,4,5,6};
  17. int[] map2 = creatIndexMap(arr2.length);
  18. printOut(arr2, map2);
  19. }
  20.  
  21. public static int[] creatIndexMap(int length) {
  22.  
  23. // Create a deque so elements can be removed from both ends
  24. Deque<Integer> tmp = new LinkedList<Integer>();
  25. for(int i = 0; i < length; i++) {
  26. tmp.add(i);
  27. }
  28.  
  29. // In alternation remove the last and first entries of tmp
  30. // and add them in reverse order to map array
  31. int[] map = new int[length];
  32. int index = length-1;
  33. while (!tmp.isEmpty()) {
  34. // Remove last element
  35. map[index--] = (int) tmp.removeLast();
  36.  
  37. // Remove first element
  38. if(!tmp.isEmpty()) {
  39. map[index--] = (int) tmp.removeFirst();
  40. }
  41. }
  42. return map;
  43. }
  44.  
  45. // Dispay results
  46. public static void printOut(int[] arr, int[] map) {
  47. System.out.println("Original array:");
  48. for(int i = 0; i < arr.length; i++) {
  49. System.out.print( arr[i] + " ");
  50. }
  51.  
  52. System.out.println();
  53. System.out.println("Index-mapped array:");
  54. for(int i = 0; i < arr.length; i++) {
  55. System.out.print( arr[map[i]] + " ");
  56. }
  57. System.out.println();
  58. }
  59. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
Original array:
1 2 3 4 5 
Index-mapped array:
3 2 4 1 5 
Original array:
1 2 3 4 5 6 
Index-mapped array:
3 4 2 5 1 6