Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythagorean Triplet using Java8

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;
}
like image 237
Sendhilkumar Alalasundaram Avatar asked Nov 30 '25 23:11

Sendhilkumar Alalasundaram


1 Answers

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 :).

like image 77
Tunaki Avatar answered Dec 03 '25 13:12

Tunaki