2

I'm looking through the Sort operator in Chapel and trying to order two arrays.

const a = [2.2, 3.3, 1.1, 4.4];
const b = [7, 10, 23, 1];

Now I want an iterator or new array that produces b in descending order of a. That is

var output = [1, 10, 7, 23];

How do I use a comparator (or, really, any method) to do this?

Brian Dolan
  • 3,086
  • 2
  • 24
  • 35

1 Answers1

2

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];
  }
}
ben-albrecht
  • 1,785
  • 10
  • 23
  • 1
    Thanks for this tip! Can you take a look at my implementation in [NumSuch](https://github.com/buddha314/numsuch/blob/develop/src/NumSuch.chpl#L52-L63) and see if I did anything stupid? – Brian Dolan Jan 04 '18 at 00:36