Skip to content

Instantly share code, notes, and snippets.

@zoeisnowooze
Forked from rust-play/playground.rs
Last active October 19, 2021 19:45
Show Gist options
  • Save zoeisnowooze/cb2f622431046c4dd126410f10023153 to your computer and use it in GitHub Desktop.
Save zoeisnowooze/cb2f622431046c4dd126410f10023153 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![allow(unused)]
fn reorder<T: Clone>(values: Vec<T>, indices: Vec<usize>) -> Vec<Option<(usize, T)>> {
let mut pairs: Vec<_> = indices.iter().zip(values).collect();
pairs.sort_by_key(|v| v.0);
let mut iter = pairs.iter().peekable();
(0..*pairs.last().unwrap().0 + 1)
.map(|i| match iter.peek() {
Some((j, _)) => {
if i == **j {
Some((i, iter.next().unwrap().1.clone()))
} else {
None
}
}
None => None,
})
.collect()
}
#[test]
fn reorder_all_indices() {
let values = vec!["C", "D", "E", "F", "G", "H"];
let indices = vec![3, 0, 4, 1, 2, 5];
let mut reordered = reorder(values, indices);
assert_eq!(Some((0, "D")), reordered[0]);
assert_eq!(Some((1, "F")), reordered[1]);
assert_eq!(Some((2, "G")), reordered[2]);
assert_eq!(Some((3, "C")), reordered[3]);
assert_eq!(Some((4, "E")), reordered[4]);
assert_eq!(Some((5, "H")), reordered[5]);
}
#[test]
fn reorder_missing_indices() {
let values = vec!["C", "D", "E", "F"];
let indices = vec![4, 0, 1, 5];
let mut reordered = reorder(values, indices);
assert_eq!(Some((0, "D")), reordered[0]);
assert_eq!(Some((1, "E")), reordered[1]);
assert_eq!(None, reordered[2]);
assert_eq!(None, reordered[3]);
assert_eq!(Some((4, "C")), reordered[4]);
assert_eq!(Some((5, "F")), reordered[5]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment