Skip to content

Instantly share code, notes, and snippets.

@noel-yap
Last active August 12, 2020 14:14
Show Gist options
  • Select an option

  • Save noel-yap/0d208f61ceb3373c9609011cff358ce9 to your computer and use it in GitHub Desktop.

Select an option

Save noel-yap/0d208f61ceb3373c9609011cff358ce9 to your computer and use it in GitHub Desktop.
Integer right triangles: https://projecteuler.net/problem=39
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