I have three vectors of the same length; A
, B
, and C
. I want to sort A
, and then apply the same reordering to B
and C
.
This is what A
, B
, and C
might contain:
A = 0, 120, 72, 48, 96, 24, 96, 48, 0, 0
B = 0.000818, -0.014796, 0.028391, -0.001460, 0.007406, 0.020932, 0.007412, 0.034635, -0.023112, -0.023108
C = 3, 1, 0, 1, 2, 3, 3, 2, 0, 1
This is the expected result:
A = 0, 0, 0, 120, 24, 48, 48, 72, 96, 96
B = 0.000818, -0.023112, -0.023108, -0.014796, 0.020932, -0.001460, 0.034635, 0.028391, 0.007406, 0.007412
C = 3, 0, 1, 1, 3, 1, 2, 0, 2, 3
(I don't necessarily need the ordering to be stable as it is in this example)
When searching for this problem, the only results I found were for other programming languages (C++, Python). I was unable to translate the C++ solution into Rust because I'm unfamiliar with C++.
I was able to translate the Python version:
use itertools::izip;
let a = &[0, 120, 72, 48, 96, 24, 96, 48, 0, 0];
let b = &[0.000818, -0.014796, 0.028391, -0.001460, 0.007406, 0.020932, 0.007412, 0.034635, -0.023112, -0.023108];
let c = &[3, 1, 0, 1, 2, 3, 3, 2, 0, 1];
let mut zipped_vectors: Vec<_> = izip!(a, b, c).collect();
zipped_vectors.sort_by_key(|tuple| tuple.0);
let a: Vec<_> = zipped_vectors.iter().map(|tuple| tuple.0).collect();
let b: Vec<_> = zipped_vectors.iter().map(|tuple| tuple.1).collect();
let c: Vec<_> = zipped_vectors.iter().map(|tuple| tuple.2).collect();
However, this is not very efficient which is a problem because efficiency is of utmost importance in my application.
How can you perform this operation efficiently in Rust?