Last active
January 17, 2022 03:22
-
-
Save juandahurt/8e8520d46562a57592a7c76b03b78567 to your computer and use it in GitHub Desktop.
Recaman sequence
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
// Usage | |
// recaman(size: 10) | |
// ouput: [0, 1, 3, 6, 2, 7, 13, 20, 12, 21] | |
import Foundation | |
func recaman(size: Int) -> [Int] { | |
var res = [Int]() | |
var counter = 1 | |
var currNumber = 0 | |
for index in 0..<size { | |
if index == 0 { | |
res.append(currNumber) | |
continue | |
} | |
let aux = currNumber - counter | |
if aux > 0 && !res.contains(aux) { | |
currNumber = aux | |
} else { | |
currNumber = currNumber + counter | |
} | |
res.append(currNumber) | |
counter += 1 | |
} | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment