我正在编写一个应用程序,用户将输入杂务和清洁工。然后数据被排序。杂务应该在清洁工之间均匀地洗牌。
//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()
1条答案
按热度按时间mrzz3bfm1#
你要把你的数组分成
cleaners.count
,在这个例子中是2。你要寻找的是杂务的数量除以清洁工的数量,四舍五入成一个整数值,如下所示:你的扩展代码也让我得了癌症。下面是一个更干净的实现:
Extension code source
cleaners.count
为模的chorse.count
值(不能除以整数),您也可以检查ceil
的行为,而不是floor
或round
。*