Created
October 27, 2018 05:07
-
-
Save SatoTakeshiX/22289c281658fe68ca040fe1efb7aef5 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
// インデックス番号を入れたらその番号のフィボナッチ数を出力 | |
func fib(index: Int) -> Int { | |
guard index > 1 else { return 1 } | |
var a = 1 | |
var b = 1 | |
(2...index).forEach { (index) in | |
(a, b) = (a + b, a) | |
} | |
return a | |
} | |
(0...10).forEach { (index) in | |
print(fib5(index: index)) | |
} | |
//出力 | |
//1 | |
//1 | |
//2 | |
//3 | |
//5 | |
//8 | |
//13 | |
//21 | |
//34 | |
//55 | |
//89 | |
// インデックス番号を入れたらそれまでのフィボナッチ数列を出力 | |
func fibSequence(index: Int) { | |
guard index > 1 else { | |
print("1") | |
return | |
} | |
var fibArray = [1, 1] | |
(2...index).forEach { (index) in | |
fibArray.append(fibArray[index-2] + fibArray[index-1]) | |
} | |
let sequence = fibArray.reduce("") { (result, value) -> String in | |
if result.isEmpty { | |
return "\(value)" | |
} else { | |
return "\(result),\(value)" | |
} | |
} | |
print(sequence) | |
} | |
fibSequence(index: 16) | |
// -> 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment