|
| 1 | +/* ____ ______________ ________________________ __________ |
| 2 | + * \ \/ / \ \/ / __/ / \ \/ / \ |
| 3 | + * \______/___/\___\______/___/_____/___/\___\______/___/\___\ |
| 4 | + * |
| 5 | + * Copyright 2021 Vavr, https://vavr.io |
| 6 | + * |
| 7 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | + * you may not use this file except in compliance with the License. |
| 9 | + * You may obtain a copy of the License at |
| 10 | + * |
| 11 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | + * |
| 13 | + * Unless required by applicable law or agreed to in writing, software |
| 14 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | + * See the License for the specific language governing permissions and |
| 17 | + * limitations under the License. |
| 18 | + */ |
| 19 | +package io.vavr.collection.euler; |
| 20 | + |
| 21 | +import io.vavr.API; |
| 22 | +import io.vavr.concurrent.Future; |
| 23 | +import org.junit.Test; |
| 24 | + |
| 25 | +import java.util.concurrent.TimeUnit; |
| 26 | + |
| 27 | +import static org.assertj.core.api.Assertions.assertThat; |
| 28 | + |
| 29 | +public class Euler44Test { |
| 30 | + |
| 31 | + /** |
| 32 | + * <strong>Problem 44 Pentagon numbers</strong> |
| 33 | + * <p> |
| 34 | + * Pentagonal numbers are generated by the formula, P<sub><i>n</i></sub>=<i>n</i>(3<i>n</i>−1)/2. |
| 35 | + * The first ten pentagonal numbers are: </p> |
| 36 | + * <p> |
| 37 | + * 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... |
| 38 | + * </p> |
| 39 | + * <p> |
| 40 | + * It can be seen that P<sub>4</sub> + P<sub>7</sub> = 22 + 70 = 92 = P<sub>8</sub>. |
| 41 | + * However, their difference, 70 − 22 = 48, is not pentagonal. |
| 42 | + * </p> |
| 43 | + * <p> |
| 44 | + * Find the pair of pentagonal numbers, P<sub><i>j</i></sub> and P<sub><i>k</i></sub>, |
| 45 | + * for which their sum and difference are pentagonal and D = |P<sub><i>k</i></sub> - P<sub><i>j</i></sub>| |
| 46 | + * is minimised; what is the value of D? |
| 47 | + * <p> |
| 48 | + * See also <a href="https://projecteuler.net/problem=44">projecteuler.net |
| 49 | + * problem 44</a>. |
| 50 | + */ |
| 51 | + @Test |
| 52 | + public void shouldSolveProblem44() { |
| 53 | + final Future<Long> computation = API.Future(this::minimalPentagonalDiff) |
| 54 | + .await(2, TimeUnit.SECONDS); |
| 55 | + assertThat(computation.getOrElse(-1L)).isEqualTo(5482660); |
| 56 | + } |
| 57 | + |
| 58 | + private Long minimalPentagonalDiff() { |
| 59 | + return Utils.pentagonal().flatMap(sumPentagonal -> |
| 60 | + Utils.pentagonal().takeWhile(pentagonal -> sumPentagonal.compareTo(pentagonal) > 0) |
| 61 | + .filter(pj -> Utils.isPentagonal(sumPentagonal - pj) && |
| 62 | + Utils.isPentagonal(sumPentagonal - 2 * pj)) |
| 63 | + .map(pj -> sumPentagonal - 2 * pj)).head(); |
| 64 | + } |
| 65 | +} |
0 commit comments