在 Chapel 中用另一个数组作为索引来排序一个数组

Order an array with another array as an index in Chapel

我正在查看 Chapel 中的 Sort 运算符并尝试对两个数组进行排序。

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

现在我想要一个迭代器或新数组,它按 a 的降序生成 b。即

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

我如何使用比较器(或者,实际上,任何方法)来做到这一点?

您可以通过将数组压缩在一起并使用 comparator 对它们进行排序来完成此操作,该 comparator 定义要排序的数组(压缩表达式的元组索引)和顺序(升序或降序)。有几种不同的方法可以实现这一点,其中一种如下所示:

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);
}

我们可以针对您的具体情况稍微简化一下。由于元组默认按第一个元素排序,我们实际上不需要创建比较器,但仍然需要使用 Sort 模块中提供的 reverseComparator 反转顺序:

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];
  }
}