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());
    }
}

Popular Prag Prog topics Top

sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=&gt; (create-...
New
simonpeter
When I try the command to create a pair of migration files I get an error. user=&gt; (create-migration "guestbook") Execution error (Ill...
New
lirux
Hi Jamis, I think there’s an issue with a test on chapter 6. I own the ebook, version P1.0 Feb. 2019. This test doesn’t pass for me: ...
New
herminiotorres
Hi! I know not the intentions behind this narrative when called, on page XI: mount() |&gt; handle_event() |&gt; render() but the correc...
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
taguniversalmachine
It seems the second code snippet is missing the code to set the current_user: current_user: Accounts.get_user_by_session_token(session["...
New
a.zampa
@mfazio23 I’m following the indications of the book and arriver ad chapter 10, but the app cannot be compiled due to an error in the Bas...
New
New
davetron5000
Hello faithful readers! If you have tried to follow along in the book, you are asked to start up the dev environment via dx/build and ar...
New
SlowburnAZ
Getting an error when installing the dependencies at the start of this chapter: could not compile dependency :exla, "mix compile" failed...
New

Other popular topics Top

AstonJ
If it’s a mechanical keyboard, which switches do you have? Would you recommend it? Why? What will your next keyboard be? Pics always w...
New
AstonJ
Or looking forward to? :nerd_face:
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
DevotionGeo
I know that -t flag is used along with -i flag for getting an interactive shell. But I cannot digest what the man page for docker run com...
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
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
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
Rails 7 completely redefines what it means to produce fantastic user experiences and provides a way to achieve all the benefits of single...
New
PragmaticBookshelf
Author Spotlight: Karl Stolley @karlstolley Logic! Rhetoric! Prag! Wow, what a combination. In this spotlight, we sit down with Karl ...
New
First poster: bot
Large Language Models like ChatGPT say The Darnedest Things. The Errors They MakeWhy We Need to Document Them, and What We Have Decided ...
New

Latest in PragProg

View all threads ❯