Skip to content

Instantly share code, notes, and snippets.

@TheMuellenator
Created April 20, 2021 15:07
Show Gist options
  • Save TheMuellenator/d7a51665386b12b11519fb43d33e1d12 to your computer and use it in GitHub Desktop.
Save TheMuellenator/d7a51665386b12b11519fb43d33e1d12 to your computer and use it in GitHub Desktop.
class Assignment {
func fibonacci(n: Int) {
// Write your code here 👇
var n1 = 0
var n2 = 1
if n == 0 {
print("Invalid")
} else if n == 1 {
print(n1)
} else if n == 2 {
print(n1, n2)
} else {
var array = [n1, n2]
for _ in 2..<n {
let n3 = n1 + n2
n1 = n2
n2 = n3
array.append(n3)
}
print(array)
}
}
}
// Test your function here for different values of n 👇
let test = Assignment()
test.fibonacci(n: 11)
@lakhvirk
Copy link

I came with this solution, I hope it looks okay ?

class Assignment {

    func fibonacci(n: Int) {

       var array: [Int] = []

        for index in 0..<n {
            if index > 1 {
                array.append(array[array.count - 1] + array[array.count - 2])
            } else {
                array.append(index)
            }
        }       
        print(array)   
    }   
}

@OsamaSaberB
Copy link

OsamaSaberB commented Apr 11, 2022

this was my way of solving.

func fibonacci(n: Int){
var array = [0,1]
var counter = 0
var numberToAdd = 0

while counter < n {
    numberToAdd = (array.last!) + array[counter]
    counter += 1
    array.append(numberToAdd)
}
array.removeLast(2) //to compensate for starting the array with 2 elements [0,1]
print(array)
}

@ilyamfaisal28
Copy link

ilyamfaisal28 commented Feb 7, 2024

This is my solution

func fibonacci(n: Int) {

    var array: [Int] = []
    for i in 0..<n {
        if i == 0 || i == 1 {
            array.append(i)
        } else {
            array.append(array[i-2] + array[i-1])
        }
    }
    print(array)
}

@salanderm
Copy link

class Assignment {
var numbers = [0, 1]
var i: Int = 0
var number: Int = 0

func fibonacci(n: Int) {
    while (i < (n-2)) {
        number = numbers[i] + numbers[i + 1]
        numbers.append(number)
        i += 1
    }
print(numbers)
}

}

@vovahvfr
Copy link

vovahvfr commented Oct 24, 2024

class Assignment {
    func fibonacci(n: Int) -> Void {
        var sequence = [0, 1]
        for _ in 2..<n {
            sequence.append(sequence[sequence.count - 1] + sequence[sequence.count - 2])
        }
        print(Array(sequence.prefix(n)))
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment