Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Given an array you need to rotate its elements K number of times in Rust

For example, an array [10,20,30,40,50,60] rotate by 2 positions to [30,40,50,60,10,20]

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