Skip to content

Instantly share code, notes, and snippets.

@NoahPeeters
Created May 14, 2017 10:42
Show Gist options
  • Save NoahPeeters/180184e3dae40f3378d78ede5048fdc2 to your computer and use it in GitHub Desktop.
Save NoahPeeters/180184e3dae40f3378d78ede5048fdc2 to your computer and use it in GitHub Desktop.
A simple swift sequence/iterator for the 3n+1 problem
class threeNPlusOne: Sequence, IteratorProtocol {
var n: UInt
init(withStartNumber startN: UInt) {
n = startN * 2 // multiply by 2 so that n is a even number and will be devided by two in the first next() call
}
func next() -> UInt? {
if n % 2 == 0 { // even
n /= 2
} else {
n = (3 * n) + 1 // odd
}
return n
}
func contains(_ element: UInt) -> Bool {
var oneCount = 0 // the only known endless loop is 4 - 2 - 1
while oneCount < 2 {
let currentNumber = self.next()
if currentNumber == element {
return true
} else if currentNumber == 1 {
oneCount += 1
}
}
return false
}
func enteredKnownEndlessLoop() -> Bool {
return n == 1 || n == 2 || n == 4
}
}
var iterator = threeNPlusOne(withStartNumber: 18);
while (true) {
let currentNumber = iterator.next()!
print(currentNumber)
if iterator.enteredKnownEndlessLoop() { break }
}
print(threeNPlusOne(withStartNumber: 18).contains(17))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment