Created
August 10, 2016 11:02
-
-
Save stuartbreckenridge/1b1ac27eea43e7ec2d775b954c5485ac to your computer and use it in GitHub Desktop.
A Swift implementation of the Collatz Conjecture, with full playground markup.
This file contains hidden or 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
import UIKit | |
//: # The Collatz Conjecture | |
//: *This process will eventually reach the number 1, regardless of which positive integer is chosen initially. (See [Wikipedia](https://en.wikipedia.org/wiki/Collatz_conjecture).)* | |
//: \ | |
//: Create an array to capture the sequence of numbers returned by the `collatz` function. | |
var sequence = [Int]() | |
//: The `collatz(start:Int, initial:Bool) -> [Int]` function takes an integer and will perform the following: | |
//:- if the integer (`n`) is 1, it will return an `[Int]` array. | |
//:- if the integer (`n`) is even, it will divide `n` by 2, append `n` to `[Int]`, and run the function again with `n`. | |
//:- if the integer (`n`) is odd, it will perform multiply `n` by 3 and add 1, add `n` to `[Int]`, and run the function again with `n`. | |
//: - note: If `initial` == `true`, the `start` variable is added to `[Int]`. | |
func collatz(start:Int, initial:Bool = true) -> [Int] { | |
var n = start | |
if initial == true { | |
sequence.append(start) | |
} | |
if n == 1 { | |
return sequence | |
} | |
else if n % 2 == 0 { | |
n /= 2 | |
sequence.append(n) | |
} | |
else { | |
n = (3 * n) + 1 | |
sequence.append(n) | |
} | |
return collatz(start: n, initial: false) | |
} | |
/*: | |
- example: The basic use case for the `collatz` function.\ | |
\ | |
The array in this example contains all values for the sequence starting at n = 27. var x = n is used to show the graph. | |
*/ | |
for n in collatz(start: 27, initial: true) { | |
var x = n | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment