是否可以对浮点进行泛型转换并返回任意数量的数组?
也许我不明白如何用数组进行任意递归?
例子
输入向量
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
}
最佳答案
不能返回可变大小的元组。你能做的就是
返回嵌套数组。
示例(希望我能正确地解释问题):
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
创建N
的“步幅”:[ x[$0], x[$0+N], x[$0+2*N], ..., x[x.count-N+$0] ]