Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java array traversal in circular manner

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.

like image 451
Connecting life with Android Avatar asked Dec 28 '11 04:12

Connecting life with Android


People also ask

How do you traverse in a circular array?

If a careful observation is run through the array, then after n-th index, the next index always starts from 0 so using the mod operator, we can easily access the elements of the circular list, if we use (i)%n and run the loop from i-th index to n+i-th index.

Why is it beneficial to use a circular array to implement a queue?

Advantages. Circular Queues offer a quick and clean way to store FIFO data with a maximum size. Conserves memory as we only store up to our capacity (opposed to a queue which could continue to grow if input outpaces output.)

What is array traversal in Java?

We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.


2 Answers

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.

like image 97
Stephen C Avatar answered Sep 19 '22 12:09

Stephen C


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);
like image 38
Timothy Jones Avatar answered Sep 18 '22 12:09

Timothy Jones