How to shuffle VecDeque?

I can shuffle a regular vector quite simply:

extern crate rand;
use rand::Rng;

fn shuffle(coll: &mut Vec<i32>) {
    rand::thread_rng().shuffle(coll);
}

The problem is that now my code needs to be used std::collections::VecDeque, which causes this code to not compile.

What is the easiest way to get around this?

+4
source share
2 answers

Unfortunately, the method is defined for shuffling fragments. Due to its own complexity constraints, a cannot store its elements in a slice, so it can never be directly called on . rand::Rng::shuffleVecDequeshuffleVecDeque

values shuffle , O (1) , VecDeque . , , , values , .

:

" " rand::Rng::shuffle :

extern crate rand;

use std::collections::VecDeque;

// Real requirement for shuffle
trait LenAndSwap {
    fn len(&self) -> usize;
    fn swap(&mut self, i: usize, j: usize);
}

// An exact copy of rand::Rng::shuffle, with the signature modified to
// accept any type that implements LenAndSwap
fn shuffle<T, R>(values: &mut T, mut rng: R)
    where T: LenAndSwap,
          R: rand::Rng {
    let mut i = values.len();
    while i >= 2 {
        // invariant: elements with index >= i have been locked in place.
        i -= 1;
        // lock element i in place.
        values.swap(i, rng.gen_range(0, i + 1));
    }
}

// VecDeque trivially fulfills the LenAndSwap requirement, but
// we have to spell it out.
impl<T> LenAndSwap for VecDeque<T> {
    fn len(&self) -> usize {
        self.len()
    }
    fn swap(&mut self, i: usize, j: usize) {
        self.swap(i, j)
    }
}

fn main() {
    let mut v: VecDeque<u64> = [1, 2, 3, 4].iter().cloned().collect();
    shuffle(&mut v, rand::thread_rng());
    println!("{:?}", v);
}
+6

VecDeque , VecDeque.html::as_mut_slices:

use rand::seq::SliceRandom; // 0.6.5;
use std::collections::VecDeque; 

fn shuffle(coll: &mut VecDeque<i32>) {
    let mut rng = rand::thread_rng();
    let (a, b) = coll.as_mut_slices();
    a.shuffle(&mut rng);
    b.shuffle(&mut rng);
}

, , . , .

-1

Source: https://habr.com/ru/post/1664090/


All Articles