12

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.

6 Answers 6

28
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.

Sign up to request clarification or add additional context in comments.

4 Comments

This entire post really reminds me of that stupid fuzz buzz problem, lots of people answering with overly complicated non-sensical solutions, when there's an easier way to do things with no effort
I gave you a +1 for the three line solution that also deals with out out bounds cases :) However, I agree with your readability concern- I think the loop looks like it's a normal iteration at first glance which may not be ideal.
How do you invent something like that? How? :D
Don't ask me. It isn't my invention. Though I don't recall where I learned it.
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);

2 Comments

what would be the value of start? i dont want to fix start value
Start is wherever you want to start the traversal in the array. To print 3 4 5 1 2, start should be 2, or to print 1 2 3 4 5 start should be 0 - maybe I've misunderstood your question?
1
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];
   }
}

Comments

1

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

Comments

1

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

1 Comment

you saved me big time.
0

Instead of using a for loop with indexes, which is harder to read, you can use Iterables from Google Guava as follows :

List<Integer> myList = List.of(1,2,3);
Iterator<Integer> myListIterator = Iterables.cycle(myList).iterator();

then you will only have to use myListIterator.next(). example :

System.out.println(myListIterator.next());
System.out.println(myListIterator.next());
System.out.println(myListIterator.next());
System.out.println(myListIterator.next());

This will print : 1 2 3 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.