Skip to content

Instantly share code, notes, and snippets.

@BrandonShega
Last active June 30, 2017 19:13
Show Gist options
  • Save BrandonShega/2b6cab94cc94aa8005a912579c8736ea to your computer and use it in GitHub Desktop.
Save BrandonShega/2b6cab94cc94aa8005a912579c8736ea to your computer and use it in GitHub Desktop.
Fibonacci Sequence
import UIKit
import XCPlayground
import PlaygroundSupport
struct FibonacciIterator: IteratorProtocol {
var (first, second) = (0,1)
mutating func next() -> Int? {
(first, second) = (second, first + second)
return first
}
}
struct FibonacciSequence: Sequence {
func makeIterator() -> FibonacciIterator {
return FibonacciIterator()
}
subscript(index: Int) -> Int {
return Array(prefix(index + 1))[index]
}
}
struct Fibonacci {
let sequence = FibonacciSequence()
func prefix(_ max: Int) -> [Int] {
return Array(sequence.prefix(max))
}
func number(at index: Int) -> Int {
return sequence[index - 1]
}
}
let fibonacci = Fibonacci()
print(fibonacci.prefix(10)) // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print(fibonacci.number(at: 6)) // 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment