本文介绍了迅速拆分数组的优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出任何类型的数组和所需数量的子数组,我需要此输出:
Given an array of any kind and the wanted number of subarray, i need this output :
print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(into: 3)) // [[0, 3, 6], [1, 4], [2, 5]]即使没有足够"的子数组,输出也必须包含正确数目的子数组.元素来填充那些:
Output must contain the correct number of subarrays even if there is not "enough" elements to fill those :
print([0, 1, 2].splitInSubArrays(into: 4)) // [[0], [1], [2], []]我现在有这个可行的实现,但是有一种更好(更优雅)的方式来实现此输出:
I have this working implementation for now but is there a better (more elegant) way of achieving this output :
extension Array { func splitInSubArrays(into size: Int) -> [[Element]] { var output: [[Element]] = [] (0..<size).forEach { var subArray: [Element] = [] for elem in stride(from: $0, to: count, by: size) { subArray.append(self[elem]) } output.append(subArray) } return output } } 推荐答案您可以用 map()操作替换两个循环:
You can replace both loops with a map() operation:
extension Array { func splitInSubArrays(into size: Int) -> [[Element]] { return (0..<size).map { stride(from: $0, to: count, by: size).map { self[$0] } } } }外部 map()将每个偏移量映射到相应的数组,内部 map()将索引映射到数组元素.
The outer map() maps each offset to the corresponding array, and the inner map() maps the indices to the array elements.
示例:
print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(into: 3)) // [[0, 3, 6], [1, 4], [2, 5]] print([0, 1, 2].splitInSubArrays(into: 4)) // [[0], [1], [2], []]更多推荐
迅速拆分数组的优雅方法
发布评论