Created
October 19, 2021 14:26
-
-
Save wperron/8191d60e3a1d5f933842b04adceeef6e to your computer and use it in GitHub Desktop.
reorder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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