Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: How can I rotate every n elements in an Array list by 1 index?

1. ## How can I rotate every n elements in an Array list by 1 index?

Hey guys! I'm still a bit new to Java and I'm working on a problem where I'm supposed to rotate every n elements in an ArrayList.
The method takes in as parameters: List<Integers> list and an integer n.

if n = 3;
If the List contains -> [0,1,2,3,4,5,6,7,8,9,10]
After the call on rotateEveryN the list should be -> [2,0,1,5,3,4,8,6,7,9,10]

I know how to go about storing the nth element in a temp variable. And how to move elements
around. But I seem to be getting confused on how to properly rotate this subset of elements within the list.

```public static void rotateEveryN(List<Integer> list, int n) {
for (int i = 0; i < list.size(); i++){
for (int j = i; j <= n; j++){       // <- I know this is where my confusion is starting
//  How can I only work on three elements at a time from within the list?
// Should the inner loop be starting back at 0 every n element?

}
}
}```

2. ## Re: How can I rotate every n elements in an Array list by 1 index?

how to properly rotate this subset of elements
Do you have a list of the steps the program must take to solve the problem? A design.
If not, work on making a list of the steps and post it before trying to write any code.
You need a design BEFORE trying to write the code.

3. ## The Following User Says Thank You to Norm For This Useful Post:

sdressesdresses (March 27th, 2019)

4. ## Re: How can I rotate every n elements in an Array list by 1 index?

You were so right. As soon as I stopped and did a little thinking. I realized that the inner loop was unnecessary if I properly incremented the first loop.
Once I did that the rest seemed to fall right into place!
``` int remainder = list.size() % n;
for (int i = 0; i < list.size() - remainder; i+=n){
int temp = list.get(i + n - 1);
list.remove(i + n - 1);
}

}```

5. ## The Following User Says Thank You to Nick0188 For This Useful Post:

sdressesdresses (March 27th, 2019)

6. ## Re: How can I rotate every n elements in an Array list by 1 index?

You don't need to call the get method. The remove method returns the removed object.