Created
April 20, 2021 15:07
-
-
Save TheMuellenator/d7a51665386b12b11519fb43d33e1d12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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)
}
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)
}
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)
}
}
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
I came with this solution, I hope it looks okay ?