Java Reference
In-Depth Information
IntStream.rangeClosed(a, 100)
.filter(b -> Math.sqrt(a*a + b*b) % 1 == 0)
.mapToObj(b ->
new int[]{a, b, (int)Math.sqrt(a * a + b * b)})
);
Okay, what's the flatMap about? First, you create a numeric range from 1 to 100 to generate
values for a. For each given value of a you're creating a stream of triples. Mapping a value of a to
a stream of triples would result in a stream of streams! The flatMap method does the mapping
and also flattens all the generated streams of triples into a single stream. As a result you produce
a stream of triples. Note also that you change the range of b to be a to 100. There's no need to
start the range at the value 1 because this would create duplicate triples (for example, (3, 4, 5)
and (4, 3, 5)).
Running the code
You can now run your solution and select explicitly how many triples you'd like to return from
the generated stream using the limit operation that you saw earlier:
pythagoreanTriples.limit(5)
.forEach(t ->
System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
This will print
3, 4, 5
5, 12, 13
6, 8, 10
7, 24, 25
8, 15, 17
Can you do better?
The current solution isn't optimal because you calculate the square root twice. One possible way
to make your code more compact is to generate all triples of the form (a*a, b*b, a*a+b*b) and
then filter the ones that match your criteria:
 
Search WWH ::




Custom Search