拆分大数组分为两个数组 [英] Split Big Array Into Two Arrays
问题描述
我有对象的大数组,并想将其拆分成包含交替次序的对象两个数组。
I have a big array of objects and would like to split it into two arrays containing the objects in alternate order.
例如:
[0,1,2,3,4,5,6]
变为这两个数组(它们应交替)
Becomes these two arrays (they should alternate)
[0,2,4,6]
和 [1,3,5]
有一吨的方式来分割阵列。但是,什么是最有效的(成本最低)如果数组是巨大的。
There are a ton of ways to split an array. But, what is the most efficient (least costly) if the array is huge.
推荐答案
有各种花哨的方式与过滤器做到这一点,但最有可能需要两次传球而不是一个,所以你可能也只是使用一个for循环。
There are various fancy ways to do it with filter but most would probably require two passes rather than one, so you may as well just use a for-loop.
预留空间,前期可以使在这种情况下,一个很大的区别,如果来源是因为大,它会避免不必要的重新分配,新的阵列成长,所需的空间计算在固定时间内的阵列。
Reserving space up-front could make a big difference in this case since if the source is large it’ll avoid unnecessary re-allocation as the new arrays grow, and the calculation of space needed is in constant time on arrays.
// could make this take a more generic random-access collection source
// if needed, or just make it an array extension instead
func splitAlternating<T>(source: [T]) -> ([T],[T]) {
var evens: [T] = [], odds: [T] = []
evens.reserveCapacity(source.count / 2 + 1)
odds.reserveCapacity(source.count / 2)
for idx in indices(source) {
if idx % 2 == 0 {
evens.append(source[idx])
}
else {
odds.append(source[idx])
}
}
return (evens,odds)
}
let a = [0,1,2,3,4,5,6]
splitAlternating(a) // ([0, 2, 4, 6], [1, 3, 5])
如果性能是真正重要的,你可以使用 source.withUnsafeBufferPointer
来访问源元素,避免了指数的边界检查。
If performance is truly critical, you could use source.withUnsafeBufferPointer
to access the source elements, to avoid the index bounds checking.
如果数组是真正巨大的,的和的你不打算使用所产生的数据,除了品尝一小数量的元素,你可以考虑使用一个懒惰的视图,而不是(虽然标准库懒惰的过滤器是没有多大用处在这里,因为它返回序列不是一个集合 - 你可能需要编写你自己的)
If the arrays are really huge, and you aren’t going to use the resulting data except to sample a small number of elements, you could consider using a lazy view instead (though the std lib lazy filter isn’t much use here as it returns sequence not a collection – you’d possibly need to write your own).
这篇关于拆分大数组分为两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!