複数の配列があり、次のように、そのうちの1つの並べ替え順序に基づいてすべてを並べ替えたいと思います。
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"]]
あらゆる種類のコレクションでこれをジェネリックにしたい場合(ただし、std libコレクションアルゴリズムと同じスタイルで配列を返します):
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) }
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加