Fibonacci numbers generator in Swift 3

fibonacci sequence
fibonacci series ios
fibonacci swift recursion
fibonacci series using function
fibonacci java
fibonacci coding
fibonacci dynamic programming python
fibonacci c++

The following Q&A covers a few methods of generating Fibonacci numbers in Swift, but it's quite outdated (Swift 1.2?):

  • Sum of Fibonacci term using Functional Swift

Question: How could we generate Fibonacci numbers neatly using modern Swift (Swift >= 3)? Preferably methods avoiding explicit recursion.

An alternative for Swift 3.0 would be to use the helper function

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)
}

from 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

Note that in order to include zero in the resulting sequence, it suffices to replace the initial value (0, 1) by (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

That makes the "artificial" check

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

redundant. The underlying reason is that the Fibonacci numbers can be generalized to negative indices (https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):

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

swift3 - Fibonacci numbers generator in Swift 3, An alternative for Swift 3.0 would be to use the helper function public func sequence<T>(first: T, while condition: @escaping (T)-> Bool, next: @escaping (T) -> T)  Swift program that implements Fibonacci method func fibonacci(n: Int) -> Int {// Some temporary variables.var a = 0 var b = 1 // Add up numbers to the desired iteration.

Fibonacci series in Swift · GitHub, Fibonacci series. // F[n] = F[n-1] + F[n-2]. // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144​. // Find the fibonacci number for n interations. func fibonacci(n: Int) {. var num1  Fibonacci series in Swift. GitHub Gist: instantly share code, notes, and snippets.

In Swift 3.1, here's an iterator that generates Fibonacci numbers forever, and an infinite sequence derived from it:

class FibIterator : IteratorProtocol {
    var (a, b) = (0, 1)

    func next() -> Int? {
        (a, b) = (b, a + b)
        return a
    }
}

let fibs = AnySequence{FibIterator()}

To print the first 10 Fibonacci numbers:

> print(Array(fibs.prefix(10)))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

If you want to filter or map this infinite sequence you'll need to call .lazy first, since otherwise filter or map will behave strictly and will not terminate. Here are the first 5 even Fibonacci numbers:

> print( Array(fibs.lazy.filter{$0 % 2 == 0}.prefix(5)) )
[2, 8, 34, 144, 610]

Fibonacci Swift playground - The Startup, What will be the total number of distinct ways you can reach to the to. This is actually same as calculating the n th number of the fibonacci series. uses many fewer multiplications than the primitive approach (three vs. eight,  Fibonacci Series using for loop in Swift. Fibonacci is a series of numbers in which each number is the sum of the two preceding numbers. This program prints the first 10 numbers in the Fibonacci Series.

Details

Xcode 9.3.1, Swift 4.1

Solution
extension Array where Element: BinaryInteger {

    private mutating func fibonacci(index: Int) {
        if index >= count {
            return
        }
        self[index] = self[index-1] + self[index-2]
        return fibonacci(index: index+1)
    }

    init(fibonacci count: Int) {
        self = [Element]()
        if count < 0 {
            self = [Element]()
        }
        self = [Element](repeating: 1, count: count)
        fibonacci(index: 2)
    }

    static func calculate(fibonacciAt index: Int) -> Element? {

        if index < 0 {
            return nil
        }

        if index < 2 {
            return 1
        }

        func calc(a: Element, b: Element, index: Int) -> Element {
            if index == 1 {
                return b
            }
            return calc(a: b, b: a+b, index: index-1)
        }

        return calc(a: 1, b: 1, index: index)
    }
}
Usage
let fibonacciSequence = [Int](fibonacci: 15)
let index = 12
print(fibonacciSequence)
print(fibonacciSequence[index])
let value = [Int].calculate(fibonacciAt: index)
print("\(value!)")
Results

Swift 3 - Fibonacci Sequence, Fibonacci Series using for loop in Swift. Fibonacci numbers. This program prints the first 10 numbers in the Fibonacci Series. Output : 0 1 1 2 3 5 8 13 21 34  About List of Fibonacci Numbers . This Fibonacci numbers generator is used to generate first n (up to 201) Fibonacci numbers. Fibonacci number. The Fibonacci numbers are the sequence of numbers F n defined by the following recurrence relation:

Details

XCode Version 10.0 beta 6, Swift 4.2

The control flow is required to get either the first or the first two iterations of the fibonacci seq starting with 0.

Time Complexity: O(n) Space Complexity: O(n)

Code

func fib(_ n: Int) -> [Int] {

 var fibs: [Int] = [0, 1]
 switch n
 {
 case 1:  return [fibs[0]]
 case 2:  return [fibs[0],fibs[1]]
 default:

 (2...n-1).forEach
 { i in
     fibs.append(fibs[i - 1] + fibs[i - 2])
 }

 return fibs
 }
}

Usage

fib(8)

//print(fib(8))

Swift Fun Algorithms #6: Fibonacci Sequence, Example code. Let us begin. We introduce fibonacci(), which receives one Int and returns another. We use three temporary variables. We use an implicit local  In mathematics, the Fibonacci sequence (sometimes wrongly called Fibonacci series) is the following infinite sequence of natural numbers: 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377 The sequence starts with 0 and 1, and thereafter each element is the addition of the previous two.

Fibonacci Series in Swift, So, I didn't really need another distraction, but Swift has an interactive func fibonacciI(n: Int) { var f1=1, f2=1, fib=0 for i in 3n { fib = f1 + f2  Mar 3, 2016 · 3 min read Probably one of the most famous algorithms ever, but still lot of people struggles when trying to find an efficient solution. Let me introduce you to the Fibonacci sequence .

Swift Fibonacci Numbers, The fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 and etc. An alternative approach might be a Fibonacci-number generator that takes a  Look at the number x 3 = 2. Every 3rd number is a multiple of 2 (2, 8, 34, 144, 610, ) Look at the number x 4 = 3. Every 4th number is a multiple of 3 (3, 21, 144, ) Look at the number x 5 = 5. Every 5th number is a multiple of 5 (5, 55, 610, ) And so on (every nth number is a multiple of x n).

Fibonacci in Swift – The Craft of Coding, Fibonacci numbers are strongly related to the golden ratio: Binet's formula expresses the n th Fibonacci number in terms of n and the golden ratio, and implies that the ratio of two consecutive Fibonacci numbers tends to the golden ratio as n increases. Fibonacci numbers are named after Italian mathematician Leonardo of Pisa, later known as

Comments
  • Nice, didn't previously know about the negative indices part!
  • Actually, it seems the the whole body of the helper sequence can be downhacked into return sequence(state: first, next: { (condition($0) ? $0 : Optional<T>.none, $0 = next($0)).0 }).
  • @dfri: No, that would compute next($0) even if the condition is not satisfied, i.e. "once too often".
  • Ah, my bad, the defer (in the original) wont be executed (reached) in case the guard breaks and returns nil?
  • @dfri: Exactly. If the defer statement is not executed then its code block is not scheduled for execution at all.
  • That reminds me of the helper function suggested in stackoverflow.com/a/40070339/1187415, which can be used quite universally. Using that, you can print the fibonacci numbers with for f in sequence(first: (0, 1), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) { print(f.1) }.
  • @MartinR That's neat indeed! I've already previously upvoted the linked answer, but if you have the time and feel up for it, an answer based on that helper would be a great addition to this thread :)
  • Please excuse me for pinging you like this, but as I think that you are interested in the performance of algorithms in Swift, I would like to invite you to have a look at codereview.stackexchange.com/q/158798/35991 and codereview.stackexchange.com/q/158799/35991 !
  • @MartinR No worries, I'm happy for the ping, thanks (will use this as a chance to take my Knuth collection out of the shelf). Will look at some evening this week, and see if I can come with some constructive advice. Btw, since you also ask for Swiftyness/semantics/etc, you might want to also ping Hamish (if you haven't already), I think he'll be interested in the subject, as well as eager to possibly help out.
  • Recursion is not necessarily evil. See an explanation and discussion here: stackoverflow.com/questions/3021/…
  • None of the other answers use recursion either: they use sequence generators.