Java Reference
In-Depth Information
Figure 5.9. The Pythagorean theorem
Representing a triple
So where do you start? The first step is to define a triple. Instead of (more properly) defining a
new class to represent a triple, you can use an array of int with three elements, for example, new
int[]{3, 4, 5} to represent the tuple (3, 4, 5). You can now access each individual component of
the tuple using array indexing.
Filtering good combinations
Let's assume someone provides you with the first two numbers of the triple: a and b. How do
you know whether that will form a good combination? You need to test whether the square root
of a * a + b * b is an integer number; that is, it has no fractional part, which in Java can be
expressed using expr % 1.0. If it's not an integer, that means c is not an integer. You can express
this requirement as a filter operation (you'll see how to connect it later to form valid code):
filter(b -> Math.sqrt(a*a + b*b) % 1 == 0)
Assuming that surrounding code has given a value for a and assuming stream provides possible
values for b, filter will select only those values for b that can form a Pythagorean triple with a.
You may be wondering what the line Math.sqrt(a*a + b*b) % 1 == 0 is about. It's basically a way
to test whether Math.sqrt(a*a + b*b) returns an integer result. The condition will fail if the
result of the square root produces a number with a decimal such as 9.1 (9.0 is valid).
 
Search WWH ::




Custom Search