Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active February 18, 2017 13:19
Show Gist options
  • Save kristopherjohnson/a6b6c322c48cba1d22feec88a8c5f688 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/a6b6c322c48cba1d22feec88a8c5f688 to your computer and use it in GitHub Desktop.
Fibonacci sequence in Swift 3
/// Returns a sequence of Fibonacci numbers.
///
/// The sequence is [1, 1, 2, 3, 5, 8, 13, ...].
///
/// The sequence is not infinite; it terminates when
/// the next value would be greater than
/// `Int.max`.
///
/// - returns: A sequence of Fibonacci numbers.
public func fibonacciSequence() -> AnySequence<Int> {
return fibSeq(initialState: (1, 1))
}
/// Returns a sequence of Fibonacci numbers, starting with 0.
///
/// The sequence is [0, 1, 1, 2, 3, 5, 8, 13, ...].
///
/// The sequence is not infinite; it terminates when
/// the next value would be greater than
/// `Int.max`.
///
/// - returns: A sequence of Fibonacci numbers.
public func fibonacciSequence0() -> AnySequence<Int> {
return fibSeq(initialState: (0, 1))
}
/// Returns a Fibonacci-like sequence.
///
/// The first two elements of the sequence are the
/// two elements of `initialState`. Each subsequent
/// element is the sum of the previous two elements.
///
/// The sequence terminates when a negative number would
/// be returned (which indicates integer addition overflow).
///
/// - parameter initialState: The first two elements of the returned sequence.
///
/// - returns: A Fibonacci-like sequence of numbers.
private func fibSeq(initialState: (Int, Int)) -> AnySequence<Int> {
let seq = sequence(state: initialState) {
(state: inout (Int, Int)) -> Int? in
let (n1, n2) = state
if n1 < 0 { return nil }
state = (n2, n1 &+ n2)
return n1
}
return AnySequence(seq)
}
// Print all elements (until overflow)
let fibs = fibonacciSequence()
for (i, n) in fibs.enumerated() {
print("\(i + 1): \(n)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment