Skip to content

Instantly share code, notes, and snippets.

@getaaron
Last active January 29, 2017 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getaaron/939e27ff62bd99aba788aae8c3f5fcbc to your computer and use it in GitHub Desktop.
Save getaaron/939e27ff62bd99aba788aae8c3f5fcbc to your computer and use it in GitHub Desktop.
Some implementations of a Fibonacci method in Swift
// The correct numbers
let expectedSequence = [1, 1, 2, 3, 5, 8, 13, 21, 34]
// Iterative
func digit(index: Int) -> Int {
var digits = [1, 1]
for i in (2...index) {
let x = digits[i-1]
let y = digits[i-2]
digits.append(x + y)
}
return digits[index]
}
// Recursive
func digit(index: Int) -> Int {
guard index > 1 else { return 1 }
let x = digit(index: index - 1)
let y = digit(index: index - 2)
let result = x + y
return result
}
// Recursive, with Caching
var cache = [Int:Int]()
func digit(index: Int) -> Int {
guard index > 1 else { return 1 }
if let cachedResult = cache[index] {
return cachedResult
}
let x = digit(index: index - 1)
let y = digit(index: index - 2)
let result = x + y
cache[index] = result
return result
}
// Iterative, as an IteratorProtocol
struct Fibonacci: IteratorProtocol {
let finalIndex: Int
init(finalIndex: Int) {
self.finalIndex = finalIndex
}
private var digits = [Int]()
mutating func next() -> Int? {
guard digits.count - 1 < finalIndex else {
return nil
}
let result: Int
if digits.count < 2 {
result = 1
} else {
let x = digits[digits.count - 1]
let y = digits[digits.count - 2]
result = x + y
}
digits.append(result)
return digits.last
}
}
extension Fibonacci: Sequence { }
for i in Fibonacci(finalIndex: 10) {
print(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment