-
Notifications
You must be signed in to change notification settings - Fork 822
Expand file tree
/
Copy pathshuffle_vec.rs
More file actions
220 lines (180 loc) · 6.4 KB
/
shuffle_vec.rs
File metadata and controls
220 lines (180 loc) · 6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use rand::{Rng, SeedableRng, rngs::SmallRng};
use std::{
ops::{Deref, DerefMut},
vec::IntoIter,
};
#[derive(Debug, Clone, Default)]
pub struct ShuffleVec<T> {
vec: Vec<T>,
indices: Option<Vec<usize>>,
/// This is primarily necessary to ensure that shuffle does not behave out of place.
///
/// For that reason we swap the first track with the currently playing track. By that we ensure
/// that the shuffle state is consistent between resets of the state because the first track is
/// always the track with which we started playing when switching to shuffle.
original_first_position: Option<usize>,
}
impl<T: PartialEq> PartialEq for ShuffleVec<T> {
fn eq(&self, other: &Self) -> bool {
self.vec == other.vec
}
}
impl<T> Deref for ShuffleVec<T> {
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
&self.vec
}
}
impl<T> DerefMut for ShuffleVec<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.vec.as_mut()
}
}
impl<T> IntoIterator for ShuffleVec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.vec.into_iter()
}
}
impl<T> From<Vec<T>> for ShuffleVec<T> {
fn from(vec: Vec<T>) -> Self {
Self {
vec,
original_first_position: None,
indices: None,
}
}
}
impl<T> ShuffleVec<T> {
pub fn shuffle_with_seed<F: Fn(&T) -> bool>(&mut self, seed: u64, is_first: F) {
self.shuffle_with_rng(SmallRng::seed_from_u64(seed), is_first)
}
pub fn shuffle_with_rng<F: Fn(&T) -> bool>(&mut self, mut rng: impl Rng, is_first: F) {
if self.vec.len() <= 1 {
info!("skipped shuffling for less or equal one item");
return;
}
if self.indices.is_some() {
self.unshuffle()
}
let indices: Vec<_> = {
(1..self.vec.len())
.rev()
.map(|i| rng.random_range(0..i + 1))
.collect()
};
for (i, &rnd_ind) in (1..self.vec.len()).rev().zip(&indices) {
self.vec.swap(i, rnd_ind);
}
self.indices = Some(indices);
self.original_first_position = self.vec.iter().position(is_first);
if let Some(first_pos) = self.original_first_position {
self.vec.swap(0, first_pos)
}
}
pub fn unshuffle(&mut self) {
let indices = match self.indices.take() {
Some(indices) => indices,
None => return,
};
if let Some(first_pos) = self.original_first_position {
self.vec.swap(0, first_pos);
self.original_first_position = None;
}
for i in 1..self.vec.len() {
match indices.get(self.vec.len() - i - 1) {
None => return,
Some(n) => self.vec.swap(*n, i),
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use rand::Rng;
use std::ops::Range;
fn base(range: Range<usize>) -> (ShuffleVec<usize>, u64) {
let seed = rand::rng().random_range(0..10_000_000_000_000);
let vec = range.collect::<Vec<_>>();
(vec.into(), seed)
}
#[test]
fn test_shuffle_without_first() {
let (base_vec, seed) = base(0..100);
let mut shuffled_vec = base_vec.clone();
shuffled_vec.shuffle_with_seed(seed, |_| false);
let mut different_shuffled_vec = base_vec.clone();
different_shuffled_vec.shuffle_with_seed(seed, |_| false);
assert_eq!(
shuffled_vec, different_shuffled_vec,
"shuffling with the same seed has the same result"
);
let mut unshuffled_vec = shuffled_vec.clone();
unshuffled_vec.unshuffle();
assert_eq!(
base_vec, unshuffled_vec,
"unshuffle restores the original state"
);
}
fn get_shuffle_vec_without_and_with_first() -> (ShuffleVec<usize>, ShuffleVec<usize>) {
const MAX_RANGE: usize = 200;
let (base_vec, seed) = base(0..MAX_RANGE);
let rand_first = rand::rng().random_range(0..MAX_RANGE);
let mut shuffled_with_first = base_vec.clone();
shuffled_with_first.shuffle_with_seed(seed, |i| i == &rand_first);
assert_eq!(
Some(&rand_first),
shuffled_with_first.first(),
"after shuffling the first is expected to be the given item"
);
let mut shuffled_without_first = base_vec.clone();
shuffled_without_first.shuffle_with_seed(seed, |_| false);
(shuffled_without_first, shuffled_with_first)
}
#[test]
fn test_shuffle_with_first() {
const MAX_VEC_RECREATION: usize = 20;
let mut prevent_running_indefinitely = 0;
let (shuffled_without_first, shuffled_with_first) = loop {
let (vec1, vec2) = get_shuffle_vec_without_and_with_first();
if vec1 != vec2 {
break (vec1, vec2);
}
// vec without and with first is equal, aka the vec first item is the same value as
// the randomly determined first values, we just create another set of two shuffled vec
assert!(
prevent_running_indefinitely < MAX_VEC_RECREATION,
"failed to retrieve two different vector after {MAX_VEC_RECREATION}"
);
prevent_running_indefinitely += 1;
};
let mut switched_positions = Vec::with_capacity(2);
for (i, shuffled_without_first_value) in shuffled_without_first.iter().enumerate() {
if shuffled_without_first_value != &shuffled_with_first[i] {
switched_positions.push(i);
} else {
assert_eq!(
shuffled_without_first_value, &shuffled_with_first[i],
"shuffling with the same seed has the same result"
);
}
}
assert_eq!(
switched_positions.len(),
2,
"only the switched positions should be different"
);
assert_eq!(
shuffled_with_first[switched_positions[0]],
shuffled_without_first[switched_positions[1]],
"the switched values should be equal"
);
assert_eq!(
shuffled_with_first[switched_positions[1]],
shuffled_without_first[switched_positions[0]],
"the switched values should be equal"
)
}
}