xcode 如何将字符串数组平均拆分为组

btqmn9zl  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(135)

我正在编写一个应用程序,用户将输入杂务和清洁工。然后数据被排序。杂务应该在清洁工之间均匀地洗牌。

//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()
mrzz3bfm

mrzz3bfm1#

你要把你的数组分成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)])
        }
    }
}

Extension code source

  • 注意:对于不是以cleaners.count为模的chorse.count值(不能除以整数),您也可以检查ceil的行为,而不是floorround。*

相关问题