我正在撰寫一個應用程式,用戶將輸入家務和清潔工。然后資料被排序。家務活應該在清潔工之間均勻地洗牌。
//this extension divides an array into chunks based on the number in the .chunked(by:)
var cleaners: [String] = ["person1", "person2"]
var chores: [String] = ["dishes", "laundry", "sweep patio", "dust", "trash","bathroom"]
var choresSorted = chores.chunked(by: cleaners.count)
extension Collection {
func chunked(by distance: Int) -> [[Element]] {
precondition(distance > 0, "distance must be greater than 0") // prevents infinite loop
var index = startIndex
let iterator: AnyIterator<Array<Element>> = AnyIterator({
let newIndex = self.index(index, offsetBy: distance, limitedBy: self.endIndex) ?? self.endIndex
defer { index = newIndex }
let range = index ..< newIndex
return index != self.endIndex ? Array(self[range]) : nil
})
return Array(iterator)
}
print as [["dishes", "laundry"], ["sweep patio", "dust"], ["trash","bathroom"]]
所以問題是家務被分成 2 組,因為有 2 名清潔工,我希望能夠將它們分成 2 組,每組 3 名
print as [["dishes", "laundry", "sweep patio"], ["dust", "trash","bathroom"]]
PS我不需要知道如何洗牌我已經知道如何使用
chores.shuffle()
uj5u.com熱心網友回復:
在示例案例中,您將陣列分塊cleaners.count
為 2。您正在尋找的是家務數量除以清潔工數量,四舍五入為整數值,如下所示:
var choresSorted = chores.chunked(by: floor(chores.count / cleaners.count))
你的擴展代碼也讓我患上了癌癥。這是一個更清潔的實作:
var cleaners: [String] = ["person1", "person2"]
var chores: [String] = ["dishes", "laundry", "sweep patio", "dust", "trash","bathroom"]
chores.shuffle()
var choresSorted = chores.chunked(by: floor(chores.count / cleaners.count))
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 size, count)])
}
}
}
擴展代碼源
注意:對于chorse.count
不是模數cleaners.count
(不分成整數)的值,您還可以檢查的行為ceil
而不是floor
或簡單地round
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516569.html
標籤:数组迅速代码排序