dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: Functional Programming in Java, Second Edition: JUnit code improvements for Chapter 11, pages 195 ff “Refactoring Nested Loops"

Nothing surprising here, just adapting the form to the other examples.

Ah yes, compute() now returns an immutable list in all cases.

package chapter11;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class NestedLoopTest {

    record Triple(int a, int b, int c) {
        public String toString() {
            return String.format("%d %d %d", a, b, c);
        }
    }

    private static Triple triple(int a, int b, int c) {
        return new Triple(a, b, c);
    }

    interface PythagoreanTriples {
        List<Triple> compute(int numberOfValues);
    }

    // (m² - n², 2 * m * n, m² + n²) is a valid triple because, resolving
    // (m⁴ + n⁴ - 2 * m² * n²) + (4 * m² * n²) = m⁴ + n⁴ + 2 * m² * n²
    // assuming m > n

    private static Triple getTripleEuclidsWay(final int m, final int n) {
        if (m <= n) {
            throw new IllegalArgumentException("m <= n");
        }
        final int a = m * m - n * n;
        final int b = 2 * m * n;
        final int c = m * m + n * n;
        return triple(a, b, c);
    }

    static class PythagoreanTriplesBefore implements PythagoreanTriples {

        public List<Triple> compute(int tripleCount) {
            if (tripleCount == 0) {
                return List.of(); // unmodifiable
            }
            List<Triple> triples = new ArrayList<>();
            for (int m = 2; ; m++) {
                for (int n = 1; n < m; n++) {
                    triples.add(getTripleEuclidsWay(m, n));
                    if (triples.size() == tripleCount)
                        break;
                }
                if (triples.size() == tripleCount)
                    break;
            }
            return Collections.unmodifiableList(triples);
        }
    }

    static class PythagoreanTriplesAfter implements PythagoreanTriples {

        public List<Triple> compute(int tripleCount) {
            return Stream.iterate(2, e -> e + 1)
                    .flatMap(m -> IntStream.range(1, m).mapToObj(n -> getTripleEuclidsWay(m, n)))
                    .limit(tripleCount)
                    .toList();
        }

    }

    private static void commonPythagoreanTriplesTests(final PythagoreanTriples pytris) {
        assertAll(
                () -> assertEquals(List.of(), pytris.compute(0)),
                () -> assertEquals(List.of(triple(3, 4, 5)),
                        pytris.compute(1)),
                () -> assertEquals(
                        List.of(triple(3, 4, 5), triple(8, 6, 10), triple(5, 12, 13)),
                        pytris.compute(3)),
                () -> assertEquals(
                        List.of(triple(3, 4, 5), triple(8, 6, 10),
                                triple(5, 12, 13), triple(15, 8, 17),
                                triple(12, 16, 20)),
                        pytris.compute(5))
        );
    }

    @Test
    void pythagoreanTriplesBefore() {
        commonPythagoreanTriplesTests(new PythagoreanTriplesBefore());
    }

    @Test
    void pythagoreanTriplesAfter() {
        commonPythagoreanTriplesTests(new PythagoreanTriplesAfter());
    }
}

Where Next?

Popular Pragmatic Bookshelf topics Top

johnp
Running the examples in chapter 5 c under pytest 5.4.1 causes an AttributeError: ‘module’ object has no attribute ‘config’. In particula...
New
belgoros
Following the steps described in Chapter 6 of the book, I’m stuck with running the migration as described on page 84: bundle exec sequel...
New
conradwt
First, the code resources: Page 237: rumbl_umbrella/apps/rumbl/mix.exs Note: That this file is missing. Page 238: rumbl_umbrella/app...
New
HarryDeveloper
Hi @venkats, It has been mentioned in the description of ‘Supervisory Job’ title that 2 things as mentioned below result in the same eff...
New
cro
I am working on the “Your Turn” for chapter one and building out the restart button talked about on page 27. It recommends looking into ...
New
adamwoolhether
When trying to generate the protobuf .go file, I receive this error: Unknown flag: --go_opt libprotoc 3.12.3 MacOS 11.3.1 Googling ...
New
jskubick
I think I might have found a problem involving SwitchCompat, thumbTint, and trackTint. As entered, the SwitchCompat changes color to hol...
New
dsmith42
Hey there, I’m enjoying this book and have learned a few things alredayd. However, in Chapter 4 I believe we are meant to see the “&gt;...
New
tkhobbes
After some hassle, I was able to finally run bin/setup, now I have started the rails server but I get this error message right when I vis...
New
Keton
When running the program in chapter 8, “Implementing Combat”, the printout Health before attack was never printed so I assumed something ...
New

Other popular topics Top

wolf4earth
@AstonJ prompted me to open this topic after I mentioned in the lockdown thread how I started to do a lot more for my fitness. https://f...
New
PragmaticBookshelf
Design and develop sophisticated 2D games that are as much fun to make as they are to play. From particle effects and pathfinding to soci...
New
Rainer
My first contact with Erlang was about 2 years ago when I used RabbitMQ, which is written in Erlang, for my job. This made me curious and...
New
AstonJ
There’s a whole world of custom keycaps out there that I didn’t know existed! Check out all of our Keycaps threads here: https://forum....
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
DevotionGeo
The V Programming Language Simple language for building maintainable programs V is already mentioned couple of times in the forum, but I...
New
gagan7995
API 4 Path: /user/following/ Method: GET Description: Returns the list of all names of people whom the user follows Response [ { ...
New
PragmaticBookshelf
Author Spotlight James Stanier @jstanier James Stanier, author of Effective Remote Work , discusses how to rethink the office as we e...
New
husaindevelop
Inside our android webview app, we are trying to paste the copied content from another app eg (notes) using navigator.clipboard.readtext ...
New
PragmaticBookshelf
Author Spotlight: Tammy Coron @Paradox927 Gaming, and writing games in particular, is about passion, vision, experience, and immersio...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: