# Trabb Pardo – Knuth - Algorithm in streams

Trabb Pardo and Knuth devised this simple procedure as a way to explore the functionality of various languages. The wiki page describes it as:

The Trabb Pardo–Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages.

The algorithm is simple:

ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
call a function to do an operation
if result overflows
alert user
else
print result


The standard 'function' is to calculate the following:

$$f(x) = \sqrt{|x|} + 5 \times x^3$$

The limiting factor is traditionally the value 400.0.

Here's the Java 8 code to accomplish the traditional 11 input values:

import java.util.Arrays;
import java.util.Scanner;
import java.util.function.IntToDoubleFunction;
import java.util.stream.IntStream;

public class TPK {

public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in);) {
int[] values = IntStream.generate(scanner::nextInt).limit(11).toArray();
int[] reversed = IntStream.range(0, values.length)
.map(index -> values[values.length - index - 1]).toArray();
IntToDoubleFunction function =
val -> Math.sqrt(Math.abs(val)) + 5 * val * val * val;
Arrays.stream(reversed)
.mapToDouble(function)
.forEach(val -> System.out.println(
val > 400.0 ? "TOO LARGE" : String.format("%.5f", val)));
}
}

}


## 1 Answer

Instead of generating an array of $N$ elements and then reversing it, I'd find it more natural to push values onto a stack and pop off one by one.

It would seem that the "standard" and "traditional" elements would be good as constants, defined near the top of the file:

• the number 11
• the function to apply
• the limit

So that you can play with them easily without making edits inside the main, unchanging part of the code.

Lastly, you have an unnecessary ; in the try statement.

The ability to unit test would be nice, though in this simple example it might take substantial refactoring and lead to over-engineering, and so might not be worth it. Just a thought anyway.