Moving java array in a circular way

I have an array that has 1 2 3 4 5 values.

array a = [ 1 , 2, 3, 4, 5] 

Now I want to go in a circle. for example, I want to print 2 3 4 5 1 or 3 4 5 1 2 or 5 1 2 3 4 and so on. any algorithm on this?

Edit: I want to print the entire combination in a circular way. I do not want to indicate the starting point at the initial stage.

+9
source share
5 answers
 int start = ... for (int i = 0; i < a.length; i++) { System.out.println(a[(start + i) % a.length]); } 

(If you want to iterate over the array in the opposite direction from start , change start + i to start - i in the array index expression.)

I should note that this is probably not the most efficient way to express a loop ... in terms of speed of execution. However, the difference is small and, most likely, does not matter.

A more important point is whether using % gives a more readable code in this way. I think it is, but maybe because I have seen / used this idiom before.

+20
source

How about the following:

 int start = // start position, must be in bounds int i = start; do { .... i++; if(i == a.length) i = 0; } while(i != start); 
+1
source
 int st = n ; // n is the starting position from where you print for(int i = st; i < a.length; i++) { -- print each array[i]; } if(st != 0) { for(int i = 0 ; i < st ; i++) { --- print each array[i]; } } 
+1
source

Basically you just need to go through the array and change the current index if necessary (for example, move it to the beginning of the array when it meets the end)

 public static void main(String[] args) { int[] array = new int[] { 1, 2, 3, 4, 5 }; System.out.println(printCircularly(array, 4)); } private static String printCircularly(int[] array, int startIndex) { StringBuilder sb = new StringBuilder(); int currentIndex = startIndex; do { sb.append(array[currentIndex++]); if (currentIndex > array.length - 1) { currentIndex = 0; } } while (currentIndex != startIndex); return sb.toString(); } 
+1
source

In addition to Stephen C's answer

 int start = ... for (int i = 0; i < a.length; i++) { System.out.println(a[(start - i + a.length) % a.length]); } 

Use this to loop back from the starting index. This is a bit unclear, but in some cases very useful. For example: user interface components such as a carousel.

And there is no ArrayIndexOutOfBoundsException !!!

+1
source

All Articles