Skip to content

Commit

Permalink
Add basic array rotation (Java/Py)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuamegnauth54 committed May 8, 2024
1 parent 42f2ae7 commit 6b2d4c7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Java/jobspls/algorithms/Cyclic.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package jobspls.algorithms;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Cyclic {
@SuppressWarnings("unchecked")
public static <T> List<T> rotate(T[] values, int by) {
var rotated = new Object[values.length];

for (var i = 0; i < values.length; ++i) {
var j = (i + by) % values.length;
rotated[j] = values[i];
}

// NOTE: Type must be T because the function takes an array of T
return Arrays.stream(rotated)
.map(v -> { return (T) v; })
.collect(Collectors.toList());
}
}
11 changes: 11 additions & 0 deletions Python/jobspls/algorithms/cyclic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from typing import Any

"""Rotate an array."""
def rotate(array: list[Any], by: int) -> list[Any]:
rotated: list[Any] = [None] * len(array)

for i, value in enumerate(rotated):
j: int = (i + by) % len(array)
rotated[j] = value

return rotated

0 comments on commit 6b2d4c7

Please sign in to comment.