For example, an array [10,20,30,40,50,60] rotate by 2 positions to [30,40,50,60,10,20]
Created
November 4, 2022 00:42
-
-
Save mykhailokrainik/02ac2387544ccdb6fd5b13c1fba60bc8 to your computer and use it in GitHub Desktop.
Given an array you need to rotate its elements K number of times in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn rotate_array<'a>(a: &'a mut [i32], mut k: i32) -> &'a [i32] { | |
let l = a.len(); | |
while k > 0 { | |
let t = a[0]; | |
let mut i = 0; | |
while i < l { | |
if i + 1 != l { | |
a[i] = a[i + 1]; | |
} else { | |
a[i] = t; | |
} | |
i += 1; | |
} | |
k -= 1 | |
} | |
a | |
} | |
// Complexity: O(k * n) Memory: O(n) | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn case_1() { | |
assert_eq!( | |
rotate_array(&mut [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6), | |
&[0, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6] | |
); | |
} | |
#[test] | |
fn case_2() { | |
assert_eq!( | |
rotate_array(&mut [10, 20, 30, 40, 50, 60], 2), | |
&[0, 30, 40, 50, 60, 10, 20] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment