Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I co-sort two Vecs based on the values in one of the Vecs?

Tags:

I have two Vecs that correspond to a list of feature vectors and their corresponding class labels, and I'd like to co-sort them by the class labels.

However, Rust's sort_by operates on a slice rather than being a generic function over a trait (or similar), and the closure only gets the elements to be compared rather than the indices so I can sneakily hack the sort to be parallel.

I've considered the solution:

let mut both = data.iter().zip(labels.iter()).collect();
both.sort_by( blah blah );
// Now split them back into two vectors

I'd prefer not to allocate a whole new vector to do this every time because the size of the data can be extremely large.

I can always implement my own sort, of course, but if there's a builtin way to do this it would be much better.

like image 631
Linear Avatar asked Sep 14 '15 12:09

Linear


People also ask

How do you sort two vectors together?

This type of sorting can be achieved using simple “ sort() ” function. By default the sort function sorts the vector elements on basis of first element of pairs.

How do you sort VEC in Rust?

Sort a Vector of Structs In order to make Person sortable you need four traits Eq , PartialEq , Ord and PartialOrd . These traits can be simply derived. You can also provide a custom comparator function using a vec:sort_by method and sort only by age.


1 Answers

I just wrote a crate "permutation" that allows you to do this :)

let names = vec!["Bob", "Steve", "Jane"];
let salary = vec![10, 5, 15];
let permutation = permutation::sort(&salary);
let ordered_names = permutation.apply_slice(&names);
let ordered_salaries = permutation.apply_slice(&salary);
assert!(ordered_names == vec!["Steve", "Bob", "Jane"]);
assert!(ordered_salaries == vec![5, 10, 15]);

It likely will support this in a single function call in the future.

like image 84
Jeremy Salwen Avatar answered Sep 19 '22 02:09

Jeremy Salwen