swift数组的每个第n个元素的平均值

时间:2016-10-13 16:03:10

标签: arrays swift

我有一个数组,我想要每个第n个元素的平均值,从特定元素开始(在这种情况下,每4个元素,从1开始)。最快的方法是什么?

我当前的方法是带有循环开关语句的for循环,但我想知道是否有更快的方法。

我想知道这样的事情是否可行:

let num_array = [1,2,3,4,5,6,7,8]
let mean4th = num_array[Array(stride(from: 1, to: num_array.count, by: 4))].reduce(0, +) / (num_array.count / 4)

希望获得mean4th = 3(即(1 + 5)/ 2)

这会返回错误

Cannot subscript a value of type 'Array<UInt8>' with an index of type 'Array<Int>'

..我正在努力解决这个问题

2 个答案:

答案 0 :(得分:1)

我不明白你的评论中Hz的意思,但是一种方法是生成你要访问的所有元素的索引并从那里迭代:

let num_array = [1,2,3,4,5,6,7,8]
let indices = Array(stride(from: 0, to: num_array.count, by: 4))

let mean = Double(indices.reduce(0) { $0 + num_array[$1] }) / Double(indices.count)

答案 1 :(得分:0)

数组不能使用序列作为下标,但你可以用不同的方式编写

  let mean4th = stride(from: 0, to: num_array.count-1, by: 4).reduce(0) {$0 + num_array[$1] } / (num_array.count / 4)

使用索引(Code Different)的想法是在正确的轨道上,但是在非常大的数组上,构建临时索引数组会增加处理时间(在500K元素数组上增加5倍)

我在500K(在操场上)上MacBook Pro的时间是0.41毫秒,远低于60Hz所需的16.7毫秒。你可能正在做的只是这个平均计算,所以越快越好。

相关问题