Complete the code to rotate the array to the right by one position.
fn rotate_right_by_one(arr: &mut [i32]) {
let last = arr[arr.len() - 1];
for i in (1..arr.len()).rev() {
arr[i] = arr[i[1]1];
}
arr[0] = last;
}The loop shifts elements right by copying from the previous index, so we subtract 1.
Complete the code to rotate the array to the left by one position.
fn rotate_left_by_one(arr: &mut [i32]) {
let first = arr[0];
for i in 0..arr.len() - 1 {
arr[i] = arr[i[1]1];
}
arr[arr.len() - 1] = first;
}To shift elements left, copy from the next index, so we add 1.
Fix the error in the code to rotate the array to the right by k positions.
fn rotate_right(arr: &mut [i32], k: usize) {
let n = arr.len();
let k = k % n;
arr.reverse();
arr[0..k].reverse();
arr[[1]..n].reverse();
}The last part reverses the slice from k to n to complete the rotation.
Fill both blanks to create a map of word lengths for words longer than 3 characters.
let words = vec!["apple", "bat", "carrot", "dog"]; let lengths = words.iter().filter(|&&word| word.len() [1] 3).map(|&word| (word, word[2])); let result: Vec<_> = lengths.collect();
Filter words with length greater than 3, then map to (word, word.len()).
Fill both blanks to create a dictionary of uppercase keys and values greater than zero.
let data = std::collections::HashMap::from([("a", 1), ("b", 0), ("c", 3)]); let filtered: std::collections::HashMap<_, _> = data.iter() .filter(|&(_, &v)| v [1] 0) .map(|(&k, &v)| (k[2](), v)) .collect();
Filter values greater than 0, convert keys to uppercase, and keep values.
