gpt4 book ai didi

arrays - 如何根据另一个数组的排序顺序对多个数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 06:09:03 26 4
gpt4 key购买 nike

我有多个数组,我想根据其中一个的排序顺序对所有数组进行排序,如下所示:

var myArr = ["b", "a", "c"]
var myArr2 = ["letter b", "letter a", "letter c"]
var myArr3 = ["b is the second letter", "a is the first letter", "c is the third letter"]

func sortMultipleArraysBasedOnOne(alphabeticallyArray:Array, arrays:[Array]){
//order myArr alphabetically
for array in arrays{
//change all arrays indexes like in myArr
}
}

sortMultipleArraysBasedOnOne(myArr, [myArr2, myArr3])

我希望函数执行后数组会是这样的:

myArr = ["a", "b", "c"]
myArr2 = ["letter a", "letter b", "letter c"]
myArr3 = ["a is the first letter", "b is the second letter", "c is the third letter"]

最佳答案

您可以通过首先根据索引值对键控数组的索引数组进行排序,然后使用 PermutationGenerator 根据这些排序的索引生成新数组来执行此操作:

let myArr = ["b", "a", "c"]
let myArr2 = ["letter b", "letter a", "letter c"]
let myArr3 = ["b is the second letter", "a is the first letter", "c is the third letter"]

func sortByKeyArray(keyArray: [String], valuesArrays: [[String]]) -> [[String]] {

precondition(reduce(valuesArrays, true) { $0.0 && ($0.1.count == keyArray.count)},
"Arrays all need to be the same length")


let permutation = sorted(indices(keyArray)) {
keyArray[$0] < keyArray[$1]
}

return valuesArrays.map {
Array(PermutationGenerator(elements: $0, indices: permutation))
}
}

sortByKeyArray(myArr, [myArr2, myArr3])
// returns [["letter a", "letter b", "letter c"], ["a is the first letter", "b is the second letter", "c is the third letter"]]

如果你想在任何类型的集合上使用这个泛型(但仍然返回一个数组,与标准库集合算法的风格相同):

func sortByKeyingCollection<C: CollectionType, D: SequenceType 
where D.Generator.Element == C,
C.Index: RandomAccessIndexType,
C.Generator.Element: Comparable>
(key: C, values: D) -> [[C.Generator.Element]] {

let permutation = sorted(indices(key)) {
key[$0] < key[$1]
}

return map(values) {
Array(PermutationGenerator(elements: $0, indices: permutation))
}
}

还有一个采用自定义比较器的版本:

func sortByKeyingCollection<C: CollectionType, D: SequenceType where D.Generator.Element == C, C.Index: RandomAccessIndexType>(key: C, values: D, isOrderedBefore: (C.Generator.Element,C.Generator.Element)->Bool) -> [[C.Generator.Element]] {

let permutation = sorted(indices(key)) {
isOrderedBefore(key[$0],key[$1])
}

return map(values) {
Array(PermutationGenerator(elements: $0, indices: permutation))
}
}


sortByKeyingCollection(myArr, [myArr2, myArr3], >)
sortByKeyingCollection(myArr, [myArr2, myArr3], lexicographicalCompare)
sortByKeyingCollection(myArr, [myArr2, myArr3]) { dropFirst($0) < dropFirst($1) }

关于arrays - 如何根据另一个数组的排序顺序对多个数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29432656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com