I am trying to move the elements in a vector to the right and then place the out of bounds element back at the beginning; a rotation of the vector.
This is pseudocode to move the first element in the vector 1 step. Since the vector is only 5 elements, the 5
goes back to the start of the vector:
let V = vec![1, 2, 3, 4, 5];
A = V.move[0].cycle();
A = [5, 1, 2, 3, 4];
The A = V.move[0].cycle();
is my attempt at this, but since Rust doesn't rotate if the index is out of bounds, it can be hard to implement.
In Python, it's possible to use the pop
function with lists:
>>>m = [1, 2, 3, 4, 5]
>>>m += [m.pop(0)]
>>>m
[2, 3, 4, 5, 1]
Using a for loop, it's possible to shift all elements to be [5, 1, 2, 3, 4]
. Is there an equivalent to the pop
function in Rust?
It would even be better if there is a function to shift elements all together.
A contiguous growable array type, written as Vec<T> , short for 'vector'.
Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents.
You are looking for [T]::rotate_right
and [T]::rotate_left
. Example (Playground):
let mut v = vec![1, 2, 3, 4, 5];
v.rotate_right(1);
println!("{:?}", v);
This outputs:
[5, 1, 2, 3, 4]
If you find yourself calling rotate_*
a lot, you should consider using a different data structures, as those methods are linear time operations. See this answer, for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With