javaarraystraversal

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.


Solution

  • 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 + a.length in the array subscript expression. The + a.length is needed because, in Java, x % y is negative when x is negative; see Best way to make Java's modulus behave like it should with negative numbers?)

    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. Maybe a comment would be warranted.