Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shift the elements inside a Rust vector to the right and put the out-of-bounds element at the beginning?

Tags:

rust

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.

like image 884
xEgoist Avatar asked Dec 10 '19 17:12

xEgoist


People also ask

What does VEC mean in Rust?

A contiguous growable array type, written as Vec<T> , short for 'vector'.

Are vectors contiguous rust?

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.


1 Answers

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.

like image 179
Lukas Kalbertodt Avatar answered Sep 20 '22 20:09

Lukas Kalbertodt