Skip to content

Instantly share code, notes, and snippets.

@jakubpetrik
Created October 2, 2015 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakubpetrik/43d3d5a63d0cd60511f4 to your computer and use it in GitHub Desktop.
Save jakubpetrik/43d3d5a63d0cd60511f4 to your computer and use it in GitHub Desktop.
Trabb─Pardo─Knuth algorithm in Swift 2.0
/**
http://rosettacode.org/wiki/Trabb_Pardo–Knuth_algorithm
The TPK algorithm is an early example of programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report
The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the
1940s and 1950s, giving several translations of the algorithm.
The task is to implement the algorithm:
1. Use the function f(x) = | x | 0.5 + 5x3
2. The overflow condition is an answer of greater than 400.
3. The 'user alert' should not stop processing of other items of the sequence.
4. Print a prompt before accepting eleven, textual, numeric inputs.
5. You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
6. The sequence S may be 'implied' and so not shown explicitly.
7. Print and show the program in action from a typical run here.
(If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
*/
import Foundation
print("Enter 11 numbers for the Trabb─Pardo─Knuth algorithm:")
let f: (Double) -> Double = { sqrt(fabs($0)) + 5 * pow($0, 3) }
(1...11)
.generate()
.map { i -> Double in
print("\(i): ", terminator: "")
guard let s = readLine(), let n = Double(s) else { return 0 }
return n
}
.reverse()
.forEach {
let result = f($0)
print("f(\($0))", result > 400.0 ? "OVERFLOW" : result, separator: "\t")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment