You can accomplish this by zipping the arrays together and sorting them with a comparator that defines which array to sort by (tuple index of the zipped expression) and the order (ascending or descending). There are a few different ways to achieve this, one of which is shown below:
use Sort;
/* Reverse comparator sorting by first element of tuple */
record Cmp {
proc key(a) return a[1];
}
// Create a comparator instance with reversed order
var cmp: ReverseComparator(Cmp);
/* Iterate over elements of array2 reverse-sorted by values of array1 */
iter zipSort(array1, array2) {
// Concatenate the arrays into an array of tuples
const AB = [ab in zip(array1, array2)] ab;
// Sort array with comparator created above
for ab in AB.sorted(comparator=cmp) {
yield ab[2];
}
}
proc main() {
const A = [2.2, 3.3, 1.1, 4.4];
const B = [7, 10, 23, 1];
// Iterator
for b in zipSort(A, B) {
writeln(b);
}
// New array
var output = zipSort(A, B);
writeln(output);
}
We can simplify this a little bit for your specific case. Since tuples sort by the first element by default, we don't actually need to create a comparator, but still need to reverse the order with the reverseComparator
provided in the Sort
module:
use Sort;
/* Iterate over elements of array2 reverse-sorted by values of array1 */
iter zipSort(array1, array2) {
// Concatenate the arrays into an array of tuples
const AB = [ab in zip(array1, array2)] ab;
// Sort array with comparator created above
for ab in AB.sorted(comparator=reverseComparator) {
yield ab[2];
}
}