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.
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.
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.)
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With