toInversions method

List<int> toInversions()

Construct a sequence of inversions from the permutation.

From wikipedia: the permutation 12043 has the inversions (0,2), (1,2) and (3,4). This would be encoded using the array { 22244 }.

Implementation

List<int> toInversions() {
  var idx = List.of(_indices, growable: false);

  for (int i = 0; i < idx.length; i++) {
    if (idx[i] != i) {
      int q = idx.indexWhere((x) => x == i, i + 1);
      var t = idx[i];
      idx[i] = q;
      idx[q] = t;
    }
  }

  return idx;
}