Skip to content

Instantly share code, notes, and snippets.

@Chiamaka
Created December 3, 2017 08:05
Show Gist options
  • Save Chiamaka/e9772ff363add7c981efe4165810e6fd to your computer and use it in GitHub Desktop.
Save Chiamaka/e9772ff363add7c981efe4165810e6fd to your computer and use it in GitHub Desktop.
//This method of solving the fibonacci sequence assumes that since the first three values never change, just state it
// and start index 3
// Fibonacci sequence example: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
// Under *Dynamic Programming*: https://www.ics.uci.edu/~eppstein/161/960109.html
// 1st iteration
func fibonacci(until: Int) {
var f = [0, 1, 1]
for i in 3...until {
f.append(f[i-2] + f[i-1])
}
print (f)
}
//2nd iteration
// Learnt about creating an array with a certain size
// Learnt about "concatenating" values to arrays
func fibonacci(until: Int) {
var sequence = Array(repeating: 0, count: until + 1) //array with certain size
sequence[1] = 1
sequence[2] = 1
for i in 3...until {
sequence[i] += sequence[i-2] + sequence[i-1] //append using +=
}
print (sequence)
}
fibonacci(until: 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment