拆分大阵中的两个元素的数组 [英] Split large Array in Array of two elements
问题描述
我有对象的大名单,我需要他们一个组UI propouse两个元素的分裂。
I have large list of objects and I need to split them in a group of two elements for UI propouse.
例如:
[0,1,2,3,4,5,6]
变得与这四个数组的数组
Becomes an array with these four arrays
[[0,1],[2,3],[4,5],[6]]
有一吨的方式来分割阵列。但是,什么是最有效的(成本最低)如果数组是巨大的。
There are a ton of ways to split an array. But, what is the most efficient (least costly) if the array is huge.
推荐答案
如果你正在寻找的效率,你可以有,将产生2个元素的每个阵列懒洋洋,所以你只存储在2个元素的方法时间在内存中:
If you're looking for efficiency, you could have a method that would generate each array of 2 elements lazily, so you'd only store 2 elements at a time in memory:
public struct ChunkGen<G : GeneratorType> : GeneratorType {
private var g: G
private let n: Int
private var c: [G.Element]
public mutating func next() -> [G.Element]? {
var i = n
return g.next().map {
c = [$0]
while --i > 0, let next = g.next() { c.append(next) }
return c
}
}
private init(g: G, n: Int) {
self.g = g
self.n = n
self.c = []
self.c.reserveCapacity(n)
}
}
public struct ChunkSeq<S : SequenceType> : SequenceType {
private let seq: S
private let n: Int
public func generate() -> ChunkGen<S.Generator> {
return ChunkGen(g: seq.generate(), n: n)
}
}
public extension SequenceType {
func chunk(n: Int) -> ChunkSeq<Self> {
return ChunkSeq(seq: self, n: n)
}
}
var g = [1, 2, 3, 4, 5].chunk(2).generate()
g.next() // [1, 2]
g.next() // [3, 4]
g.next() // [5]
g.next() // nil
此方法适用于任何序列类型
,而不仅仅是阵列。
This method works on any SequenceType
, not just Arrays.
有关雨燕1,未经协议扩展,你有:
For Swift 1, without the protocol extension, you've got:
public struct ChunkGen<T> : GeneratorType {
private var (st, en): (Int, Int)
private let n: Int
private let c: [T]
public mutating func next() -> ArraySlice<T>? {
(st, en) = (en, en + n)
return st < c.endIndex ? c[st..<min(en, c.endIndex)] : nil
}
private init(c: [T], n: Int) {
self.c = c
self.n = n
self.st = 0 - n
self.en = 0
}
}
public struct ChunkSeq<T> : SequenceType {
private let c: [T]
private let n: Int
public func generate() -> ChunkGen<T> {
return ChunkGen(c: c, n: n)
}
}
func chunk<T>(ar: [T], #n: Int) -> ChunkSeq<T> {
return ChunkSeq(c: ar, n: n)
}
这篇关于拆分大阵中的两个元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!