自定义操作将已排序的数组拆分为Swift中的子数组

时间:2018-04-19 15:06:44

标签: arrays swift collections

我想在执行以下操作的已排序 <% String leavetype = request.getParameter("leavetype");//after get value,you can pass it to query sql. %> (或ArrayCollection,无论如何)上编写自定义操作:

从头开始,它会查看每对相邻的元素。如果两者之间满足条件,则转到下一对,否则将其拆分。所以最后,我会得到一个数组数组,其中条件在同一个子数组中的元素之间得到满足,但不在不同的子数组之间。以下是否正确有效?

Sequence

1 个答案:

答案 0 :(得分:1)

您的代码无法正常运行,因为:

  • 您不会比较相邻的元素。
  • 首先将第一个元素与自身进行比较,这可能会导致 到永不停止的循环。
  • 未正确处理空数组。

以下是您的方法的工作变体:

extension Array {
    public func splitSorted(by condition: (Element, Element)->(Bool)) -> [[Element]] {
        var result = [[Element]]()
        var start = startIndex
        while start != endIndex {
            var end = start
            repeat {
                end += 1
            } while end != endIndex && condition(self[end - 1], self[end])
            result.append(Array(self[start..<end]))
            start = end
        }
        return result
    }
}

示例:

let arr = [1, 2, 3, 2, 3, 4, 3, 4, 5]
let split = arr.splitSorted(by: <)
print(split) // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Sequence的概括将是:

extension Sequence {
    public func splitSorted(by condition: (Element, Element)->(Bool)) -> [[Element]] {
        var it = makeIterator()
        guard var currentElem = it.next() else {
            return [] // Input sequence is empty
        }
        var result = [[Element]]()
        var currentSegment = [currentElem]
        while let nextElem = it.next() {
            if condition(currentElem, nextElem) {
                // Append to current segment:
                currentSegment.append(nextElem)
            } else {
                // Start new segment:
                result.append(currentSegment)
                currentSegment = [nextElem]
            }
            currentElem = nextElem
        }
        result.append(currentSegment)
        return result
    }
}

示例(按相同奇偶校验分组斐波那契数字):

// From https://stackoverflow.com/a/40203183/1187415
let fibs = sequence(state: (0, 1),
                    next: { (pair: inout (Int, Int)) -> Int? in
                        defer { pair = (pair.1, pair.0 + pair.1) }
                        return pair.1
                    })

print(fibs.prefix(12).splitSorted(by: { ($0 - $1) % 2 == 0 }))
// [[1, 1], [2], [3, 5], [8], [13, 21], [34], [55, 89], [144]]