Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Last active November 30, 2016 12:55
Show Gist options
  • Save davepkennedy/99a05cd59374643ead402bf3f9e8ae17 to your computer and use it in GitHub Desktop.
Save davepkennedy/99a05cd59374643ead402bf3f9e8ae17 to your computer and use it in GitHub Desktop.
Rotating an array by a certain amount (2 ways)
def rotate (array, amount):
return array[amount:] + array[:amount]
package io.github.davepkennedy;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dakennedy on 29/11/2016.
*/
public class Rotator {
public static List<Integer> simpleRotate (List<Integer> numbers, int amount) {
List<Integer> intermediate = new ArrayList<>();
while (intermediate.size() < numbers.size()) {
intermediate.add(numbers.get(amount));
amount += 1;
if (amount >= numbers.size()) {
amount = 0;
}
}
return intermediate;
}
public static List <Integer> complexRotate (final List<Integer> numbers, int amount) {
List <Integer> result = new ArrayList<>(numbers);
List <Integer> subList = result.subList(0, amount);
result.addAll(subList);
return result.subList(amount, result.size());
}
}
@davepkennedy
Copy link
Author

Doing it in python looks cool

  • What's happening under the hood? It could be akin to the Java approach when it comes to join the slices
  • How efficient is it with lots of data?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment