Hi, New to writing
Vinayak
Posted on November 7, 2023
def test_response(args)
print args[:happy_reacts]
end
I hope to write at least once a week on dev.to . It's a request to the dev.to community to support me and others like me to write more.
Now going ahead I just want to add a small code snippet to rotate the array in rust.
it was pratice problem in hackerearth
I'll just explain here what i wrote in Rust(new to rust so your feedback is valuable in comments).
The video has better explanation.
The first step was to get the number of test cases.
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read input");
let t: usize = input.trim().parse().expect("Invalid input");
then loop form 0 to t
for _ in 0..t {
}
inside the loop add another input to get the length of array and the times that rotation has to performed.
let mut input_n_k = String::new();
io::stdin().read_line(&mut input_n_k).expect("Failed to read input");
let mut nk = input_n_k.trim().split_whitespace();
let n: usize = nk.next().unwrap().parse().expect("Invalid input");
let k: usize = nk.next().unwrap().parse().expect("Invalid input");
following that another input stream to get the array and store in a Vector of i32 type. (i32 was within limits of the test cases)
let mut input_arr = String::new();
io::stdin().read_line(&mut input_arr).expect("Failed to read input");
let mut elements: Vec<i32> = input_arr.trim().split_whitespace()
.map(|x| x.parse().expect("Invalid input"))
.collect();
now before performing the array rotation it is good practice sanitise the rotation times and the length of the array
let k = k % n; // Handle cases where k is larger than n
now create a new array to store the results
let mut result: Vec<i32> = Vec::with_capacity(n);
the actual rotation operation
for i in 0..n {
let new_index = (n + i - k) % n;
result.push(elements[new_index]);
}
the magic of rotation happens when the new_index is created.
e.g., if n =5 and k =2
in this rotation loop
new_index = (5+0-2)%5 = 3
new_index = (5+1-2)%5 = 4
new_index = (5+2-2)%5 = 0
new_index = (5+3-2)%5 = 1
new_index = (5+5-2)%5 = 3
the new_index variable denotes the current index and when to push in the result array.
finally print the result and a new line to continue
for i in 0..n {
print!("{} ", result[i]);
}
println!();
This was simple array manipulation question solved using Rust.
The concepts of Rust used here are mutables,loops and Vectors.
Posted on November 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.