SwiftSnippetRustProgrammingAlgorithm
Last updated at 2023-07-30

Algorithm Test: Cyclic Rotation

ClickUp
Note
AI Status
Last Edit By
Last edited time
Jul 30, 2023 02:55 PM
Metatag
Slug
algorithm-test-cyclic-rotation
Writer
Published
Published
Date
Jul 30, 2023
Category
Swift
Snippet
Rust
Programming
Algorithm
🚨
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. ([1,3,4,5,6] 0)
  1. ([1,3,4,5,6] 1)
  1. ([1,3,4,5,6] 2)
  1. ([1,3,4,5,6] 3)
  1. ([1,3,4,5,6] 4)
  1. ([1,3,4,5,6] 5)

Example Output

  1. [1,3,4,5,6]
  1. [6,1,3,4,5]
  1. [5,6,1,3,4]
  1. [4,5,6,1,3]
  1. [3,4,5,6,1]
  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() }

Discussion (0)

Related Posts