Index of element in sorted()

╄→尐↘猪︶ㄣ 提交于 2019-12-02 03:24:52

You could pass into sorted not a collection of elements, but the indices of the elements:

let a = ["hello","i","must","be","going"]
let idxs = sorted(indices(a)) { a[$0] < a[$1] }
// produces [3, 4, 0, 1, 2]

Or, if you don't like capturing a and wanted the elements themselves passed into the closure, you could pass in a sequence of pairs of the index and the element, like so:

let pairs = sorted(Zip2(indices(a),a)) {
    $0.1 < $1.1
}

Note the result would be an array of (index,element) pairs: [(3, be), (4, going), (0, hello), (1, i), (2, must)]. If you wanted to turn that back into just the elements, you can do map(pairs) { $0.1 }

Also, if you take the just-indices route and want to turn that back into elements later, you can do it with PermutationGenerator:

let values = PermutationGenerator(elements: a, indices: idxs)
println(" ".join(values)) // prints "be going hello i must"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!