Skip to content

Instantly share code, notes, and snippets.

@wperron
Created October 19, 2021 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/8191d60e3a1d5f933842b04adceeef6e to your computer and use it in GitHub Desktop.
Save wperron/8191d60e3a1d5f933842b04adceeef6e to your computer and use it in GitHub Desktop.
reorder
/// Given an array of objects A, and an array of indexes B, reorder the objects in array A with the given indexes in array B.
/// Example:
/// let a = [C, D, E, F, G, H];
/// let b = [3, 0, 4, 1, 2, 5];
/// $ reorder(a, b) // a is now [D, F, G, C, E, H]
fn main() {
let res = reorder(vec!["C", "D", "E", "F", "G", "H"], vec![3, 0, 4, 1, 2, 5]);
println!("{:?}", &res)
}
fn reorder<T: Clone + Copy>(vals: Vec<T>, idx: Vec<usize>) -> Vec<T> {
let mut ret: Vec<T> = vals.clone();
for (pos, i) in idx.iter().enumerate() {
ret[i.clone()] = vals[pos];
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment