gpt4 book ai didi

swift - Swift 3 中的斐波那契数生成器

转载 作者:可可西里 更新时间:2023-10-31 23:57:49 26 4
gpt4 key购买 nike

下面的问答涵盖了一些在 Swift 中生成斐波那契数列的方法,但它已经过时了(Swift 1.2?):

问题:我们如何使用现代 Swift (Swift >= 3) 巧妙地生成斐波那契数列?最好是避免显式递归的方法。

最佳答案

Swift 3.0 的替代方法是使用辅助函数

public func sequence<T>(first: T, while condition: @escaping (T)-> Bool, next: @escaping (T) -> T) -> UnfoldSequence<T, T> {
let nextState = { (state: inout T) -> T? in
// Return `nil` if condition is no longer satisfied:
guard condition(state) else { return nil }
// Update current value _after_ returning from this call:
defer { state = next(state) }
// Return current value:
return state
}
return sequence(state: first, next: nextState)
}

来自 Express for loops in swift with dynamic range :

for f in sequence(first: (0, 1), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) {
print(f.1)
}
// 1 1 2 3 5 8 13 21 34

请注意,为了在结果序列中包含零,它足以将初始值 (0, 1) 替换为 (1, 0):

for f in sequence(first: (1, 0), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) {
print(f.1)
}
// 0 1 1 2 3 5 8 13 21 34

这使得“人工”检查成为可能

if pair.1 == 0 { pair.1 = 1; return 0 }

冗余。根本原因是斐波那契数列可以推广到负指数(https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):

 ... -8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, ...

关于swift - Swift 3 中的斐波那契数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40203182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com