Last active
August 12, 2020 14:14
-
-
Save noel-yap/0d208f61ceb3373c9609011cff358ce9 to your computer and use it in GitHub Desktop.
Integer right triangles: https://projecteuler.net/problem=39
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Triple { | |
| public final int a; | |
| public final int b; | |
| public final int c; | |
| private Triple(final int a, final int b, final int c) { | |
| this.a = a; | |
| this.b = b; | |
| this.c = c; | |
| } | |
| public static Optional<Triple> of(final int a, final int b) { | |
| final double c = Math.pow(a * a + b * b, .5); | |
| final long cRounded = Math.round(c); | |
| if (cRounded == c) { | |
| return Optional.of(new Triple(a, b, (int) cRounded)); | |
| } else { | |
| return Optional.empty(); | |
| } | |
| } | |
| } | |
| public class Solution { | |
| private List<Triple> findTriples(final int p) { | |
| return IntStream.range(2, p - 1) | |
| .mapToObj(i -> Triple.of(i, p - i)) | |
| .filter(Optional::isPresent) | |
| .map(Optional::get) | |
| .collect(Collectors.toList()); | |
| } | |
| private int findLargestSolutionSize(final int maxP) { | |
| int result = 0; | |
| List<Triple> largest = Collections.emptyList(); | |
| for (int p = 3; p < maxP + 1; ++p) { | |
| final List<Triple> contender = findTriples(p); | |
| if (contender.size() > largest.size()) { | |
| largest = contender; | |
| result = p; | |
| } | |
| } | |
| return result; | |
| } | |
| @Test | |
| public void eyeballTest() { | |
| System.out.println(findLargestSolutionSize(1000)); | |
| } | |
| public static void main(String[] args) { | |
| JUnitCore.main("Solution"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment