MCPcopy Create free account
hub / github.com/davidgiven/luje / rotate

Method rotate

lib/java/util/Collections.java:2047–2090  ·  view source on GitHub ↗

Rotates the elements in list by the distance dist e.g. for a given list with elements [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], calling rotate(list, 3) or rotate(list, -7) would modify the list to look like this: [8, 9, 0, 1, 2, 3, 4, 5, 6, 7] @param lst the list whose elements

(List<?> lst, int dist)

Source from the content-addressed store, hash-verified

2045 * integer. Negative values rotate the list backwards.
2046 */
2047 @SuppressWarnings("unchecked")
2048 public static void rotate(List<?> lst, int dist) {
2049 List<Object> list = (List<Object>) lst;
2050 int size = list.size();
2051
2052 // Can't sensibly rotate an empty collection
2053 if (size == 0) {
2054 return;
2055 }
2056
2057 // normalize the distance
2058 int normdist;
2059 if (dist > 0) {
2060 normdist = dist % size;
2061 } else {
2062 normdist = size - ((dist % size) * (-1));
2063 }
2064
2065 if (normdist == 0 || normdist == size) {
2066 return;
2067 }
2068
2069 if (list instanceof RandomAccess) {
2070 // make sure each element gets juggled
2071 // with the element in the position it is supposed to go to
2072 Object temp = list.get(0);
2073 int index = 0, beginIndex = 0;
2074 for (int i = 0; i < size; i++) {
2075 index = (index + normdist) % size;
2076 temp = list.set(index, temp);
2077 if (index == beginIndex) {
2078 index = ++beginIndex;
2079 temp = list.get(beginIndex);
2080 }
2081 }
2082 } else {
2083 int divideIndex = (size - normdist) % size;
2084 List<Object> sublist1 = list.subList(0, divideIndex);
2085 List<Object> sublist2 = list.subList(divideIndex, size);
2086 reverse(sublist1);
2087 reverse(sublist2);
2088 reverse(list);
2089 }
2090 }
2091
2092 /**
2093 * Searches the {@code list} for {@code sublist} and returns the beginning

Callers

nothing calls this directly

Calls 5

reverseMethod · 0.95
sizeMethod · 0.65
getMethod · 0.65
setMethod · 0.65
subListMethod · 0.65

Tested by

no test coverage detected