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
Hi Brian, Looks like the api for tinydb has changed a little. Noticed while working on chapter 7 that the .purge() call to the db throws...
New
yulkin
your book suggests to use Image.toByteData() to convert image to bytes, however I get the following error: "the getter ‘toByteData’ isn’t...
New
mikecargal
Title: Hands-on Rust: question about get_component (page 295) (feel free to respond. “You dug you’re own hole… good luck”) I have somet...
New
brunogirin
When installing Cards as an editable package, I get the following error: ERROR: File “setup.py” not found. Directory cannot be installe...
New
jwandekoken
Book: Programming Phoenix LiveView, page 142 (157/378), file lib/pento_web/live/product_live/form_component.ex, in the function below: d...
New
andreheijstek
After running /bin/setup, the first error was: The foreman' command exists in these Ruby versions: That was easy to fix: gem install fore...
New
bjnord
Hello @herbert ! Trying to get the very first “Hello, Bracket Terminal!" example to run (p. 53). I develop on an Amazon EC2 instance runn...
New
mcpierce
@mfazio23 I’ve applied the changes from Chapter 5 of the book and everything builds correctly and runs. But, when I try to start a game,...
New
dachristenson
@mfazio23 Android Studio will not accept anything I do when trying to use the Transformations class, as described on pp. 140-141. Googl...
New
dachristenson
I’ve got to the end of Ch. 11, and the app runs, with all tabs displaying what they should – at first. After switching around between St...
New

Other popular topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1031 17377 381
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
Thanks to @foxtrottwist’s and @Tomas’s posts in this thread: Poll: Which code editor do you use? I bought Onivim! :nerd_face: https://on...
New
AstonJ
Just done a fresh install of macOS Big Sur and on installing Erlang I am getting: asdf install erlang 23.1.2 Configure failed. checking ...
New
AstonJ
I ended up cancelling my Moonlander order as I think it’s just going to be a bit too bulky for me. I think the Planck and the Preonic (o...
New
AstonJ
If you are experiencing Rails console using 100% CPU on your dev machine, then updating your development and test gems might fix the issu...
New
PragmaticBookshelf
Build highly interactive applications without ever leaving Elixir, the way the experts do. Let LiveView take care of performance, scalabi...
New
AstonJ
Seems like a lot of people caught it - just wondered whether any of you did? As far as I know I didn’t, but it wouldn’t surprise me if I...
New
PragmaticBookshelf
Author Spotlight: Sophie DeBenedetto @SophieDeBenedetto The days of the traditional request-response web application are long gone, b...
New
CommunityNews
A Brief Review of the Minisforum V3 AMD Tablet. Update: I have created an awesome-minisforum-v3 GitHub repository to list information fo...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: