java array traversal in circular manner

北城余情 提交于 2019-12-02 23:49:14
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.

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

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

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!!!

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