使用通用步幅拆分数组?

时间:2016-11-26 22:02:57

标签: arrays swift generics

这是否可以对浮点进行泛型转换并返回任意数量的数组?

也许我不明白如何使用数组进行任意递归?

示例 输入向量

Vector:[CGFloat] = [-0.23,-5.2,0.24,-1.4,4.0,10.2]

输出向量,如果步幅为2

VectorOut=[[-0.23,0.24,4.0],[-5.2,-1.4,10.2]]

输出向量,如果步幅为3

VectorOut=[[-0.23,-1.4],[-5.2,4.0],[0.24.10.2]]


func splitArray<T:FloatingPoint>(Vector x:[T], byStride N: Int)->([T],[T],...[byStride])
{
  guard (x.count % byStride == 0) else {"BOMB \(#file) \(#line) \(#function)"
  return [NaN]
}       

var index:[Int] = [Int](repeating: 0.0, count: byStride)
var bigVector:[[T]] = [T](repeating: 0.0, count: byStride)

for idx in index {

 for elem in stride(from:idx, to: x.count - 1 - idx, by:byStride){
 bigVector[idx]=x[idx]
  }
 }
return bigVector


}

1 个答案:

答案 0 :(得分:1)

您无法返回可变大小的元组。你能做的就是 返回一个嵌套数组。

示例(希望我正确解释问题):

func splitArray<T>(vector x:[T], byStride N: Int) -> [[T]] {
    precondition(x.count % N == 0, "stride must evenly divide the array count")
    return (0..<N).map { stride(from: $0, to: x.count, by: N).map { x[$0] } }
}

let a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

print(splitArray(vector: a, byStride: 2))
// [[1.0, 3.0, 5.0], [2.0, 4.0, 6.0]]

print(splitArray(vector: a, byStride: 3))
// [[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]

说明: (0..<N).map { ... }创建一个大小为N的数组。 对于每个值$0

stride(from: $0, to: x.count, by: N).map { x[$0] }

从索引x开始$0创建“步幅”,增量为{​​{1}}:

N