java array traversal in circular manner

痴心易碎 提交于 2019-12-09 04:24:46

问题


I have an array which have 1 2 3 4 5 values.

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

Now i want to traverse it in circular manner. like 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 all the combination in circular manner. i don't want to state starting point at its initial phase.


回答1:


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

(If you want to iterate the array backwards from start, change start + i to start - i in the array subscript expression.)

I should note that this is probably not the most efficient way of expressing the loop ... in terms of execution speed. However, the difference is small, and most likely irrelevant.

A more relevant point is whether using % in this way gives more readable code. I think it does, but maybe that's because I've seen / used this particular idiom before.




回答2:


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);



回答3:


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];
   }
}



回答4:


Basically you just need to loop through the array, and change the current index if necessary (like move it to the start 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();
}



回答5:


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 for reverse loop from start index. It's a little unclear, but in some cases very useful. For example: UI components like carousel.

And there's no ArrayIndexOutOfBoundsException!!!



来源:https://stackoverflow.com/questions/8651965/java-array-traversal-in-circular-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!