I am trying to find all pythagorean triplets below a given number using Java8.
I tried to solve the problem with the code shown below. But, I am still mutating the triplets list.
I would want to know ways in which the below code can be implemented without mutating the list.
public static List<Triplet> returnPythogoreanTriplets(int num) {
List<Triplet> triplets = new ArrayList();
IntStream.rangeClosed(1, num).forEach(hyp->{
IntStream.range(1, hyp)
.forEach(side1->{
IntStream.rangeClosed(1, side1)
.forEach(side2->{
Triplet t = new Triplet<>(side2, side1, hyp);
if(t.isPythagorean()){
triplets.add(t);
System.out.println(t);
}
});
});
});
return triplets;
}
The following will do that
public static List<Triplet> returnPythogoreanTriplets(int num) {
return IntStream.rangeClosed(1, num).boxed().flatMap(hyp ->
IntStream.range(1, hyp).boxed().flatMap(side1 ->
IntStream.rangeClosed(1, side1).mapToObj(side2 -> new Triplet(side2, side1, hyp))
)
)
.filter(Triplet::isPythagorean)
.collect(Collectors.toList());
}
The trick is to flatMap on each IntStream and turn them into a Stream<Triplet>. Unfortunately, since there are no flatMapToObj for converting an IntStream into a Stream<T>, we need to call boxed() to turn it into a Stream<Integer> before.
Sample code (with an appropriate toString() on the class Triplet):
public static void main(String[] args) {
System.out.println(returnPythogoreanTriplets(3));
// prints "[Triplet [a=1, b=1, c=2], Triplet [a=1, b=1, c=3], Triplet [a=1, b=2, c=3], Triplet [a=2, b=2, c=3]]"
}
As a side-note, this is very slow brute-force implementation to build the pythagorean triplets :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With