如何根据两个数组的顺序对三个数组进行排序。迅速

时间:2016-03-26 21:23:48

标签: arrays swift sorting methods

我能想到的唯一方法是在第一次基于评级的排序之后,我将所有具有相同评级的名称组合在一起,并根据数量对该组进行排序。这有点复杂,我想我需要实现一个函数来完成它。有没有更短的方法呢?感谢。

// **Expected result**
//     sortedNameArray = ["b", "e", "a", "f", "c", "g", "d", "h"]
//   sortedRatingArray = [ 5,   5,   4,   3,   3,   3,   2,   2 ]
// sortedQuantityArray = [ 4,   3,   3,   5,   3,   2,   4,   3 ]


let nameArray     = ["a", "b", "c", "d", "e", "f", "g", "h"]
let ratingArray   = [ 4,   5,   3,   2,   5,   3,   3,   2]
let quantityArray = [ 3,   4,   3,   4,   3,   5,   2,   3]

let firstNameArray = Array(zip(nameArray, ratingArray)).sort { $0.1 > $1.1 }.map { $0.0 }
let firstRatingArray = Array(zip(ratingArray, ratingArray)).sort { $0.1 > $1.1 }.map { $0.0 }
let firstQuantityArray = Array(zip(quantityArray, ratingArray)).sort { $0.1 > $1.1 }.map { $0.0 }

// first sorting based on rating
firstNameArray      // = ["b", "e", "a", "c", "f", "g", "d", "h"]
firstRatingArray    // = [5, 5, 4, 3, 3, 3, 2, 2]
firstQuantityArray  // = [4, 3, 3, 3, 5, 2, 4, 3]

// second sorting based on quantity. 

1 个答案:

答案 0 :(得分:4)

不是维护需要同步的三个数组,而是维护一个简单结构的单个数组。

struct Entry {
    let name: String
    let rating: Int
    let quantity: Int
}

let entries = [ Entry(name: "a", rating: 4, quantity: 3),
                Entry(name: "b", rating: 5, quantity: 4),
                Entry(name: "c", rating: 3, quantity: 3),
                Entry(name: "d", rating: 2, quantity: 4),
                Entry(name: "e", rating: 5, quantity: 3),
                Entry(name: "f", rating: 3, quantity: 5),
                Entry(name: "g", rating: 3, quantity: 2),
                Entry(name: "h", rating: 2, quantity: 3),
]

let sortedEntries = entries.sort { lhs, rhs in
    if lhs.rating != rhs.rating {
        return lhs.rating > rhs.rating
    }

    return lhs.quantity > rhs.quantity
}

有了这个,你的算法应该变得微不足道,并且需要更少的计算。

如果你在某些时候需要单独的数组,解压缩它是微不足道的(虽然我很少在实践中发现这一点):

let nameArray = entries.map { $0.name }