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

jon
Some minor things in the paper edition that says “3 2020” on the title page verso, not mentioned in the book’s errata online: p. 186 But...
New
telemachus
Python Testing With Pytest - Chapter 2, warnings for “unregistered custom marks” While running the smoke tests in Chapter 2, I get these...
New
jesse050717
Title: Web Development with Clojure, Third Edition, pg 116 Hi - I just started chapter 5 and I am stuck on page 116 while trying to star...
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
jeremyhuiskamp
Title: Web Development with Clojure, Third Edition, vB17.0 (p9) The create table guestbook syntax suggested doesn’t seem to be accepted ...
New
jgchristopher
“The ProductLive.Index template calls a helper function, live_component/3, that in turn calls on the modal component. ” Excerpt From: Br...
New
jskubick
I’m under the impression that when the reader gets to page 136 (“View Data with the Database Inspector”), the code SHOULD be able to buil...
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
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
roadbike
From page 13: On Python 3.7, you can install the libraries with pip by running these commands inside a Python venv using Visual Studio ...
New

Other popular topics Top

Exadra37
I am thinking in building or buy a desktop computer for programing, both professionally and on my free time, and my choice of OS is Linux...
New
dasdom
No chair. I have a standing desk. This post was split into a dedicated thread from our thread about chairs :slight_smile:
New
brentjanderson
Bought the Moonlander mechanical keyboard. Cherry Brown MX switches. Arms and wrists have been hurting enough that it’s time I did someth...
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
gagan7995
API 4 Path: /user/following/ Method: GET Description: Returns the list of all names of people whom the user follows Response [ { ...
New
AstonJ
Biggest jackpot ever apparently! :upside_down_face: I don’t (usually) gamble/play the lottery, but working on a program to predict the...
New
PragmaticBookshelf
Build efficient applications that exploit the unique benefits of a pure functional language, learning from an engineer who uses Haskell t...
New
hilfordjames
There appears to have been an update that has changed the terminology for what has previously been known as the Taskbar Overflow - this h...
New
PragmaticBookshelf
Fight complexity and reclaim the original spirit of agility by learning to simplify how you develop software. The result: a more humane a...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: