You may find this algorithm test somewhere else. Because my source prohibits me from reproducing the question, I will just give you a question hint, and you will be presented with the solution.
The Question
You are given arbitrary input in the form of an array of numbers.
Rotate the array K times!
Example Input
- ([1,3,4,5,6] 0)
- ([1,3,4,5,6] 1)
- ([1,3,4,5,6] 2)
- ([1,3,4,5,6] 3)
- ([1,3,4,5,6] 4)
- ([1,3,4,5,6] 5)
Example Output
- [1,3,4,5,6]
- [6,1,3,4,5]
- [5,6,1,3,4]
- [4,5,6,1,3]
- [3,4,5,6,1]
- [1,3,4,5,6]
The Solution
Swift
public func cyclicRotation(_ array : inout [Int], rotationCount: Int) -> [Int] { if array.count == rotationCount || rotationCount == 0 || array.isEmpty { return array } let rotation = rotationCount % array.count let range = 0...(array.count - 1 - rotation) let firstPick = array[range] array.removeSubrange(range) return array + firstPick }
Rust
fn cyclic_rotation(array: &mut [i32], rotation_count: usize) -> Vec<i32> { if array.len() == rotation_count || rotation_count == 0 || array.is_empty() { return array.to_vec(); } let rotation = rotation_count % array.len(); let range = 0..(array.len() - rotation); let first_pick = array[range].to_vec(); array.drain(range); array.extend_from_slice(&first_pick); array.to_vec() }