โ˜ฐ
\(\newcommand \ensuremath [1]{#1}\) \(\newcommand {\toprule }[1][]{\hline }\) \(\let \midrule \toprule \) \(\let \bottomrule \toprule \) \(\def\textemdash{\unicode{x2014}}\) \(\renewcommand {\vec }{\boldsymbol }\) \(\newcommand {\Edge }{\ensuremath {\,\textemdash \,}}\) \(\newcommand \Const [1]{\text {\textsf {#1}}}\) \(\DeclareMathOperator {\lerp }{lerp}\) \(\DeclareMathOperator {\bitlen }{bitlen}\) \(\DeclareMathOperator {\sign }{sign}\) \(\newcommand {\I }{\mathrm {i}}\) \(\newcommand \AND {\mathbin {\&}}\) \(\newcommand \OR {\mathbin {|}}\) \(\newcommand \XOR {\mathbin {{}^{\wedge }}}\) \(\newcommand \shl {\ll }\) \(\newcommand \shr {\ggg }\) \(\newcommand \asr {\gg }\) \(\newcommand \NOT {\ensuremath {\mathord {\sim }}}\) \(\newcommand {\isep }{\mathrel {{.}\,{.}}}\) \(\newcommand {\Id }[1]{\mathit {#1}}\) \(\newcommand {\const }[1]{\mathsf {#1}}\) \(\newcommand {\algorithmname }[1]{\text {\textsc {#1}}}\) \(\newcommand {\bits }[1]{\text {#1}}\) \(\newcommand {\hexa }[1]{\mathtt {0x#1}}\) \(\newcommand {\num }[1]{#1}\) \(\newcommand {\qed }{\quad \square }\) \(\newcommand {\idiv }[2]{\lfloor #1/#2\rfloor }\) \(\newcommand \attribdot {\ensuremath {\mkern 1.5mu.\mkern 1.5mu}}\) \(\newcommand \attribxr [2]{#1\attribdot \text {#2}}\) \(\newcommand \attribir [2]{\Id {#1}\attribdot \text {#2}}\) \(\newcommand \attribii [2]{\Id {#1}\attribdot \Id {#2}}\) \(\newcommand \textsc [1]{#1}\) \(\newcommand {\intertext }[1]{\text {#1}\notag \\}\)

Appendix C Answers to Exercises

Preface

[0.1]

“One, but he’ll have to install what he calls a ”Lightbulb Virtual Machine” that takes up half the basement. The bulb itself will be twice as big as a normal bulb, but you can control it from anywhere in the house.” [52]

[0.2]

The answer is \(n(n+1)/2\) minutes. For \(n=1\) this is true because \(1(1+1)/2=1\). Otherwise, we first let \(n-1\) programmers change the first \(n-1\) light bulbs, which by induction takes \((n-1)n/2\) minutes. But the \(n\)th programmer is convinced that his way of changing bulbs is superior, so he spends \(n\) minutes changing all bulbs again, which gives us a total of \((n-1)n/2+n=n(n+1)/2\) minutes.

Chapter 1

[1.1]

The result is \(2\vec {p}-\vec {q}=\vec {p}+(\vec {p}-\vec {q})\). Geometrically, this is the reflection of \(\vec {q}\) across \(\vec {p}\).

[1.2]

If \((x,y)\) and \((x',y')\) are the coordinates of the two points, their distance is given by the Pythagorean theorem

\begin{equation*} \sqrt {(x-x')^2 + (y-y')^2}. \end{equation*}

The implementation is shown in Listing C.1.

Listing C.1ch1โ€ฏ/โ€ฏPoint

// Euclidean distance between two points.
public static double distance(Point a, Point b) {
    double dx = a.x - b.x, dy = a.y - b.y;
    return Math.sqrt(dx * dx + dy * dy);
}

JDK: Math
•Point

[1.3]

Since each step moves the point toward one of the triangle’s corners, the point must end up inside the triangle after a finite number of iterations. The chaos game therefore always converges toward the Sierpiński triangle, regardless of the point’s initial position. If the corners do not form an equilateral triangle, the resulting fractal is a skewed Sierpiński triangle.

[1.4]

a)If the coordinates of the points are \((x_1, y_1),\dots ,(x_n,y_n)\), the edges of the bounding box can be found by computing the minimum and maximum of the x- and y-coordinates, respectively:

\begin{align*} R_l &= \min (x_1,\dots ,x_n),& R_r &= \max (x_1,\dots ,x_n),\\ R_b &= \min (y_1,\dots ,y_n),& R_t &= \max (y_1,\dots ,y_n). \end{align*}

b)This is a special case of part (a): the bounding box of two rectangles is the bounding box of their eight corners, so we have

\begin{align*} R_l &= \min (A_l, B_l),& R_r &= \max (A_r, B_r),\\ R_b &= \min (A_b, B_b),& R_t &= \max (A_t, B_t). \end{align*}

c)The edges of the intersection of \(A\) and \(B\) are

\begin{align*} R_l &= \max (A_l, B_l),& R_r &= \min (A_r, B_r),\\ R_b &= \max (A_b, B_b),& R_t &= \min (A_t, B_t). \end{align*}

d)The implementation of Rectangle is shown in Listing C.2. The methods width(), height(), isEmpty(), contains(), and intersection() simply implement the formulas discussed in the previous parts. The boundingBox() method iterates over all points to determine the largest and smallest coordinates along both axes and then returns a Rectangle that encloses all points.

Listing C.2ch1โ€ฏ/โ€ฏRectangle

// An axis-aligned rectangle.
public record Rectangle(Point bottomLeft, Point topRight) {
    // The width and height of the rectangle.
    public double width() {return topRight.x() - bottomLeft.x();}
    public double height() {return topRight.y() - bottomLeft.y();}

    // Is the rectangle empty?
    public boolean isEmpty() {return width() < 0 || height() < 0;}

    // Determine whether 'p' lies inside the rectangle.
    public boolean contains(Point p) {
        return bottomLeft.x() <= p.x() && p.x() <= topRight.x()
                && bottomLeft.y() <= p.y() && p.y() <= topRight.y();
    }

    // Return intersection of 'this' and 'r'.
    public Rectangle intersection(Rectangle r) {
        return new Rectangle(
                new Point(Math.max(bottomLeft.x(), r.bottomLeft.x()),
                        Math.max(bottomLeft.y(), r.bottomLeft.y())),
                new Point(Math.min(topRight.x(), r.topRight.x()),
                        Math.min(topRight.y(), r.topRight.y())));
    }

    // The smallest rectangle that includes all points in the list.
    public static Rectangle boundingBox(List<Point> points) {
        double left, right, bottom, top;
        left = bottom = Double.POSITIVE_INFINITY;
        right = top = Double.NEGATIVE_INFINITY;
        for (Point p : points) {
            left = Math.min(left, p.x());
            right = Math.max(right, p.x());
            bottom = Math.min(bottom, p.y());
            top = Math.max(top, p.y());
        }
        return new Rectangle(new Point(left, bottom),
                new Point(right, top));
    }
}

[1.5]

a)The determinants are \(D_0=0\), \(D_1\approx {}0.72\), \(D_2\approx {}0.1\), and \(D_3\approx {}-0.11\). The determinant associated with \(f_0\) vanishes since the function projects every point onto the y-axis, and the one associated with \(f_3\) is negative since the leafs on the left side of the fern are mirrored.

b)A simple solution is to choose probabilities that are proportional to the absolute values of the corresponding determinants. If there are \(N\) affine transformations \(f_k = \vec {A}_k\vec {p}+\vec {t}_k\), we can set the probabilities to

\[ p_k = \frac {|\det \vec {A}_k|}{N},\qquad D = \sum _{k=0}^{N-1}|\det \vec {A}_k|. \]

The disadvantage of this choice is that the chaos game will assign no points to any function whose determinant is zero. To ensure that at least a small fraction of all points ends up in every part of the fractal, we can add a small constant \(\gamma \) to every determinant:

\[ p_k = \frac {|\det \vec {A}_k| + \gamma }{D+N\gamma },\qquad D = \sum _{k=0}^{N-1}|\det \vec {A}_k|. \]

[1.6]

a)One possible implementation of polar() is shown in Listing C.3.

Listing C.3ch1โ€ฏ/โ€ฏPoint

// Construct a point from its polar coordinates.
public static Point polar(double radius, double angle) {
    return new Point(radius * Math.cos(angle),
            radius * Math.sin(angle));
}

b)The radius \(r\) is simply the point’s distance from the origin and the angle \(\phi \) can be obtained inverting the identity \(\tan \phi =y/x\)

\begin{equation*} r = \sqrt {x^2 + y^2},\qquad \phi = \tan ^{-1}y/x. \end{equation*}

The code in Listing C.4 uses sqrt() to compute the square root and atan2() to compute the arc tangent of the ratio \(y/x\).

Listing C.4ch1โ€ฏ/โ€ฏPoint

// The radius in polar coordinates.
public double radius() {
    return Math.sqrt(x * x + y * y);
}

// The angle in polar coordinates.
public double angle() {return Math.atan2(y, x);}

JDK: Math
•Point

d)Figure C.1 shows a few examples of shapes obtained by varying the number of corners and the factor \(\alpha \). Each of the resulting shapes is self-similar and consists of \(n\) smaller copies of itself, which in turn consist of \(n\) smaller copies, and so on. Empirically, the chaos game converges for all \(0<\alpha <2\) and diverges for values of \(\alpha \) outside this range. For \(0.5<\alpha <1.5\) the resulting shapes are self-similar.

(image)

Figure C.1. IFS fractals based on regular polygons

[1.7]

a)The IFSPainter class in Listing C.5 can be used to draw point sets to a bitmap image. The class has three fields: the BufferedImage that holds the result, an instance of Graphics2D that is used to draw to this image, and the radius of each point in the coordinate system used by graphics.

Listing C.5ch1โ€ฏ/โ€ฏIFSPainter

// Create images of point sets produced using iterated function systems.
public class IFSPainter {
    private BufferedImage image;  // resulting raster image
    private Graphics2D graphics;  // graphics context for image
    private double radius;  // scaled radius of a single point

    public void drawPoints(List<Point> points) {
        for (Point p : points) {
            graphics.fill(
                    new Ellipse2D.Double(p.x(), p.y(), radius, radius));
        }
    }

    // ...
}

The constructor in Listing C.6 takes the list of points, the desired size of the image in pixels, and the radius of each point in pixels. First, image is initialized to a BufferedImage whose long side has imageLongSize pixels and that has the same aspect ratio as the point set being drawn. We then create a graphics context for this image and store it in graphics. The coordinate system is set up in such a way that the point set completely fills the image. Finally, the member variable radius is set to the radius of each point in the scaled coordinate system.

Listing C.6ch1โ€ฏ/โ€ฏIFSPainter

public IFSPainter(List<Point> points, int longSide,
        double pointRadius) {
    // Create an image with the same aspect ratio as the point set
    var region = Rectangle.boundingBox(points);
    double scaleFactor = longSide
            / Math.max(region.width(), region.height());
    image = new BufferedImage(
            (int) Math.round(region.width() * scaleFactor),
            (int) Math.round(region.height() * scaleFactor),
            BufferedImage.TYPE_INT_ARGB);
    radius = pointRadius / scaleFactor;

    // Initialize graphics context
    graphics = image.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(Color.BLACK);
    graphics.translate(0, image.getHeight());
    graphics.scale(scaleFactor, -scaleFactor);
    graphics.translate(-region.bottomLeft().x(),
            -region.bottomLeft().y());
}

b)See Fig. C.2.

(image)

Figure C.2. Fractals generated using affine IFSs

[1.8]

a)To show that \(h\) is an affine transformation, plug in the definitions of \(f\) and \(g\) and reorder the terms:

\begin{align*} \label {eq:blendifsproof} \lerp (f(\vec {p}), g(\vec {p}), t) &= (1-t)(\vec {F}\vec {p}+ \vec {f}) + t(\vec {G}\vec {p}+\vec {g})\\ &= (1-t)(\vec {F}\vec {p}) + t(\vec {G}\vec {p}) + (1-t)\vec {f}+ t\vec {g}\\ &= ((1-t)\vec {F} + t\vec {G})\vec {p} + (1-t)\vec {f}+ t\vec {g}\\ &= \lerp (\vec {F}, \vec {G}, t)\vec {p} + \lerp (\vec {f}, \vec {g},t). \end{align*}

b)The first step is to extend the lerp function to scalar values and affine transformations, as shown in Listing C.7. We can then define a function blend() that mixes two instances of AffineIFS and their probabilities using linear interpolation. If the function systems differ in size, the smaller function system is extended using affine transformations in which all coefficients are 0 (nullTransform) and whose probability are set to 0 as well.

Listing C.7ch1โ€ฏ/โ€ฏIFSBlend

static double lerp(double x, double y, double t) {
    return (1 - t) * x + t * y;
}

static Affine lerp(Affine x, Affine y, double t) {
    return new Affine(
            lerp(x.a(), y.a(), t), lerp(x.b(), y.b(), t),
            lerp(x.c(), y.c(), t), lerp(x.d(), y.d(), t),
            lerp(x.tx(), y.tx(), t), lerp(x.ty(), y.ty(), t));
}

public static AffineIFS blend(AffineIFS f, AffineIFS g, double t) {
    int n = f.transforms.length, m = g.transforms.length;
    int size = Math.max(n, m);
    Affine[] transforms = new Affine[size];
    double[] frequencies = new double[size];
    Affine nullTransform = new Affine(0, 0, 0, 0, 0, 0);
    for (int i = 0; i < size; i++) {
        transforms[i] = lerp(i < n ? f.transforms[i] : nullTransform,
                i < m ? g.transforms[i] : nullTransform, t);
        frequencies[i] = lerp(i < n ? f.probabilities[i] : 0,
                i < m ? g.probabilities[i] : 0, t);
    }
    return new AffineIFS(transforms, frequencies);
}

Chapter 2

[2.2]

By writing \(z=x+\I {}y\) and \(c=c_x+\I {}c_y\), the expression \(z^2+c\) can be expanded as follows:

\begin{align*} z^2+c &= (x + \I {}y)^2 + (c_x + \I {}c_y)\\ &= x^2 - y ^2 + 2\I {}xy + c_x + \I {}c_y\\ &= (x^2 - y ^2 + c_x) + \I {}(2xy +c_y) &&\text {because $\I ^2=-1$} \end{align*}

[2.3]

A black-and-white image of the Mandelbrot set can be created by constructing a color palette that is completely white, except for the last color, which is set to black. The two grayscale palettes can be initialized as follows:

for (int i = 0; i < colors.length; i++) {
    float g = 1 - i / (float) (colors.length - 1);
    colors[i] = new Color(g, g, g).getRGB();
}

JDK: Color

and

for (int i = 0; i < colors.length; i++) {
    float g = 0.5f + 0.5f * (float) Math.sin(2.f * i);
    colors[i] = new Color(g, g, g).getRGB();
}

JDK: Color, Math

The two resulting grayscale images are shown in Fig. C.3.

(image) (image)

Figure C.3. Grayscale renditions of the Mandelbrot set

[2.4]

To compute the Nebulabrot shown in Fig. C.4, we first compute three histograms by calling Buddhabrot.computeHistogram() with different iteration limits. We then combine these histograms by mapping them to separate color channels, as shown in Listing C.8.

(image)

Figure C.4. The Nebulabrot. The image is obtained by combining three different renderings of the Buddhabrot.

Listing C.8ch2โ€ฏ/โ€ฏBuddhabrot

public static void drawNebulabrot(
        int numTrajectories, BufferedImage image) {
    var bb = new Buddhabrot(image.getWidth(), image.getHeight());
    int[][] histoR = bb.computeHistogram(numTrajectories, 5000);
    int[][] histoG = bb.computeHistogram(numTrajectories, 500);
    int[][] histoB = bb.computeHistogram(numTrajectories, 50);
    float maxR = 0.3f * maximum(histoR);
    float maxG = 0.3f * maximum(histoG);
    float maxB = 0.3f * maximum(histoB);
    for (int y = 0; y < image.getHeight(); y++) {
        for (int x = 0; x < image.getWidth(); x++) {
            float r = Math.min(histoR[y][x] / maxR, 1.0f);
            float g = Math.min(histoG[y][x] / maxG, 1.0f);
            float b = Math.min(histoB[y][x] / maxB, 1.0f);
            image.setRGB(x, image.getHeight() - 1 - y,
                    new Color(r, g, b).getRGB());
        }
    }
}

[2.5]

a)The escapeTime() method in Listing C.9 computes the escape time of the Mandelbrot iteration. In contrast to our previous implementation, this function takes not just the parameter \(c\) but also the starting point \(z_0\) as arguments. We can use this escapeTime() method to render the Julia set as follows:

for (int y = 0; y < image.getHeight(); y++) {
    for (int x = 0; x < image.getWidth(); x++) {
        double x0 = xMin + x * pixelSize;
        double y0 = yMin + y * pixelSize;
        image.setRGB(x, image.getHeight() - 1 - y,
                colors[JuliaSet.escapeTime(cx, cy, x0, y0,
                        maxIterations)]);
    }
}

For Julia sets we keep \(c\) constant and vary the starting point \(z_0\).

Listing C.9ch2โ€ฏ/โ€ฏJuliaSet

// Compute the escape time for the Julia set.
public static int escapeTime(double cx, double cy,
        double x0, double y0, int maxIterations) {
    double escapeRadius = 2.0;
    double xn = x0, yn = y0;
    for (int k = 0; k < maxIterations; k++) {
        if (xn * xn + yn * yn > escapeRadius * escapeRadius)
            return k;
        double x = xn, y = yn;
        xn = x * x - y * y + cx;
        yn = 2 * x * y + cy;
    }
    return maxIterations;
}

[2.6]

a)Listing C.10 shows an implementation of the Game of Life. To store the state of all cells, we define two arrays of Boolean values, one for the current generation (grid) and one for the next (next). The size of both arrays is \(\mathtt {height}\times \mathtt {width}\).

Listing C.10ch2โ€ฏ/โ€ฏGameOfLife

public class GameOfLife {
    public final int width, height;
    private boolean[][] grid, next;

    public GameOfLife(int width, int height) {
        this.width = width;
        this.height = height;
        this.grid = new boolean[height][width];
        this.next = new boolean[height][width];
    }

    public void set(int x, int y, boolean value) {
        int row = Math.floorMod(y, height);
        int col = Math.floorMod(x, width);
        grid[row][col] = value;
    }

    public int get(int x, int y) {
        int row = Math.floorMod(y, height);
        int col = Math.floorMod(x, width);
        return grid[row][col] ? 1 : 0;
    }

    public void advance() {
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int n = get(x - 1, y - 1) + get(x, y - 1)
                        + get(x + 1, y - 1) + get(x - 1, y)
                        + get(x + 1, y) + get(x - 1, y + 1)
                        + get(x, y + 1) + get(x + 1, y + 1);
                next[y][x] =
                        get(x, y) == 1 ? (n == 2 || n == 3) : n == 3;
            }
        }
        var tmp = grid;
        grid = next;
        next = tmp;
    }
}

JDK: Math

The get() and set() methods read and change the state of individual cells. We translate coordinates \((x,y)\) on the infinite grid to the finite domain of size \(\mathtt {width}\times {}\mathtt {height}\) using the modulo operator:

\begin{align*} x' = x\bmod \mathtt {width},\qquad y' = y\bmod \mathtt {height}. \end{align*} We use the floorMod() function to implement these formulas, which is similar to the % operator but always returns a nonnegative number.

The advance() method computes the next game state from the current one by updating every cell. The function counts for each grid point how many of its eight neighbors are alive and sets the corresponding cell in next to either empty or alive. To make it appear as if all cells were updated at once, the code uses two separate arrays: grid holds the current cells and next the cells of the next generation. After computing the next state, the two arrays are swapped: next becomes current state, and grid is recycled and used to hold the new state in the next round.

b)The R-pentomino grows and evolves over hundreds of generations before it finally settles in a stable configuration. The LWSS moves horizontally and advances by \(2\) cells every \(4\) cycles. The abbreviation LWSS stands for lightweight spaceship; it is another example of a spaceship.

c)The following table summarizes the behavior of life forms that consists of \(n\) cells in a row:

.
\(n\) Behavior
1, 2 disappears after 1 generation
3 oscillates
4 stable after 2 generations
5 oscillates after 6 generations
6 disappears after 12 generations
7 stable after 14 generations
8 stable after 48 generations
9 oscillates after 20 generations
10 oscillates after 2 generations

d)The life form in Fig. 2.8 “inverts” the stream of gliders that moves toward the bottom left. If we write the incoming stream of gliders as “111010000…”, the outgoing stream of gliders is “000101111…”, the inverse of the input.

Chapter 3

[3.1]

The loop can be replaced by a recursive function f() that prints the current value of i and then calls itself as long as i < 10:

void f(int i) {
    if (i >= 10) 
        return;
    System.out.println(i):
    f(i + 1);
}

To print the numbers between 0 and \(10\), you call f(0) with the starting value 0.

[3.2]

Assume we are given a non-empty list \(X=x_0\ldots x_n\) and split it into a left part \(L=x_0\ldots x_{k-1}\) and a right part \(R=x_k\ldots x_n\); the position \(k\) at which we perform the split doesn’t matter. It’s now easy to see that the reverse of \(X\) is equal to the reverse of \(R\) followed by the reverse of \(L\):

\begin{equation*} \text {reverse}(X)=\text {reverse}(R)\text {reverse}(L) \end{equation*}

Listing C.11 shows an implementation of this technique.

Listing C.11ch3โ€ฏ/โ€ฏReverseList

static List<Integer> reverse(List<Integer> list) {
    if (list.size() <= 1)
        return list;
    var left = list.subList(0, list.size() / 2);
    var right = list.subList(list.size() / 2, list.size());
    var result = new ArrayList<>(reverse(right));
    result.addAll(reverse(left));
    return result;
}

[3.3]

To derive the formula for \(C\), we simply plug the definition of \(B\) into \(A\) and reorder the resulting terms:

\begin{equation*} A(B(\vec {p})) = \vec {A}(\vec {B}\vec {p}+\vec {b})+\vec {a} = (\vec {A}\vec {B})\vec {p} + (\vec {A}\vec {b} + \vec {a}). \end{equation*}

On the right-hand side, the matrix product \(\vec {A}\vec {B}\) produces a \(2\times 2\)-matrix and the expression \(\vec {A}\vec {b} + \vec {a}\) is a vector, so the result does in fact have the form of an affine transformation. If we set \(\vec {C}=\vec {A}\vec {B}\) and \(\vec {c}=\vec {A}\vec {b} + \vec {a}\), we obtain Eq. (3.4).

[3.4]

A recursive algorithm for computing whirl shapes is shown in Listing C.12. The arguments of whirl() are the corners of the base shape, a parameter fraction that determines where the corners of the nested shapes are placed along the edges of shape, and depth, the number of nested shapes that should be computed. The resulting polygons are stored as a nested list of points in result. The helper method nested() computes the corners of the nested polygon by moving each corner of shape toward the next corner. The iterative solution can be obtained by using a for loop to compute the list of nested shapes.

Listing C.12ch3โ€ฏ/โ€ฏWhirl

public void whirl(List<Point> shape, double fraction, int depth,
        List<List<Point>> result) {
    if (depth > 0) {
        result.add(shape);
        whirl(nested(shape, fraction), fraction, depth - 1, result);
    }
}

static List<Point> nested(List<Point> shape, double fraction) {
    int n = shape.size();
    var nested = new ArrayList<Point>(n);
    for (int i = 0; i < n; i++) {
        nested.add(Point.lerp(shape.get(i), shape.get((i + 1) % n),
                fraction));
    }
    return nested;
}

[3.6]

The drawPlant() function shown in Listing C.13 draws recursive plants similar to those shown in Fig. 3.5. The arrays factors[] and angles[] hold the parameters of the plants and remain unchanged, and g is the graphics context that is used for drawing the lines. The remaining parameters specify the geometry of the current branch: its starting point start, its length, and the current angle. Each invocation of drawPlant() draws the current branch as a line from start to its endpoint, which is determined by the values of length and angle. Each sub-plant is then drawn by calling drawPlant() recursively, with the length multiplied by factors[i] and the angle increased by angles[i].

Listing C.13ch3โ€ฏ/โ€ฏRecursivePlant

public static void drawPlant(double[] factors, double[] angles,
        Point start, double length, double angle, int depth,
        Graphics g) {
    if (depth <= 0)
        return;
    Point direction = Point.polar(length, angle);
    Point end = new Point(start.x() + direction.x(),
            start.y() + direction.y());
    g.drawLine((int) start.x(), (int) start.y(),
            (int) end.x(), (int) end.y());
    for (int i = 0; i < factors.length; i++) {
        drawPlant(factors, angles, end, length * factors[i],
                angle + angles[i], depth - 1, g);
    }
}

[3.7]

a)Listing C.14 shows two implementations of the Fibonacci function. The recursive implementation fibRec() is a direct translation of the definitions (3.7) and (3.8). Since \(F_0=0\) and \(F_1=1\), the function simply returns the value of \(n\) itself if \(n\le 1\). For all other values of \(n\), fibRec() calls itself recursively to compute \(F_{n-1}\) and \(F_{n-2}\) and then returns their sum. To compute the \(n\)th Fibonacci number iteratively, we start with the pair of numbers \((0,1)\) and repeatedly apply the mapping \((a,b)\mapsto (b,a+b)\):

\begin{equation*} (0,1)\to (1,1)\to (1,2)\to (2,3)\to (3,5)\to \dots \end{equation*}

The \(n\)th Fibonacci number is the first number of the \(n\)th pair in this sequence.

Listing C.14ch3โ€ฏ/โ€ฏFibonacci

public static int fibRec(int k) {
    if (k <= 1)
        return k;
    return fibRec(k - 1) + fibRec(k - 2);
}

public static int fib(int n) {
    int a = 0, b = 1;
    for (int i = 0; i < n; i++) {
        int next = a + b;
        a = b;
        b = next;
    }
    return a;
}

b)The first few Fibonacci trees are shown in Fig. C.5. The first two Fibonacci trees consists of a single node. The others are obtained by attaching the previous two trees to a new root node.

(-tikz- diagram)

Figure C.5. The first five Fibonacci trees

c)As you can see in Fig. 3.6, the width of a Fibonacci tree of order \(k\) is proportional to the number of leaves in the tree. Let’s call the number of leaves of an order-\(k\) tree \(L_k\). The first two Fibonacci trees consist of just a single node, so we have

\begin{equation} L_0 = L_1 = 1 \end{equation}

In all other cases, \(L_k\) is the number of leaves in the left subtree plus the number of leaves in the right subtree. Since the left subtree is a Fibonacci tree of order \(n-1\) and the right subtree a Fibonacci tree of order \(n-2\), we have

\begin{equation} L_k = L_{k-1} + L_{k-2},\qquad \text {for $k\ge 2$}. \end{equation}

The recursive definition of \(L_k\) is therefore almost identical to the definition of the Fibonacci numbers themselves and only differ for \(k=0\). It’s not hard to see that

\begin{equation} L_k = F_{k+1}. \end{equation}

For example, the number of leaves in Fig. 3.6 is \(F_9=21+13=34\). The height of a Fibonacci tree of order \(k\) is usually simply \(k\), except for \(k=0\) where the height is 1.

d)A program for constructing the Fibonacci tree of a given order is shown in Listing C.15. The parameter bottomLeft is the coordinate of the bottom-left corner of the entire tree. If the order is 0 or 1, we place a single leaf node at bottomLeft. Otherwise, we first compute the left and rigth subtrees and then the position of the root node. The lower-left corner of the left subtree is bottomLeft and the right subtree is moved right and up to align the two subtrees at the top. The root node is placed centered above the two subtrees. The functions width() and height() compute the width and height of a Fibonacci tree using the formulas we derived in the part (c).

Listing C.15ch3โ€ฏ/โ€ฏFibonacciTree

public static double width(int order) {
    return fib(order + 1);
}

public static double height(int order) {
    return Math.max(order, 1.0);
}

public static void drawFibonacciTree(int order, Point bottomLeft) {
    if (order <= 1) {
        System.out.printf("%d at %s%n", fib(order), bottomLeft);
    } else {
        double leftWidth = width(order - 1);
        double rightWidth = width(order - 2);
        double leftHeight = height(order - 1);
        double rightHeight = height(order - 2);
        drawFibonacciTree(order - 1, bottomLeft);
        var originRight = new Point(
                bottomLeft.x() + leftWidth,
                bottomLeft.y() + leftHeight - rightHeight);
        drawFibonacciTree(order - 2, originRight);
        var rootPosition = new Point(
                bottomLeft.x() + (leftWidth + rightWidth - 1) / 2,
                bottomLeft.y() + leftHeight);
        System.out.printf("%d at %s%n", fib(order), rootPosition);
    }
}

JDK: Math, System
•Point: Point()

[3.8]

a)The key insight is that the largest disk can only be moved from A to B if the three small disks are on the rightmost peg. The four-disk problem can therefore be solved by first moving the three smallest disks from A to C, then the largest disk from A to B, and finishing by moving three disks from C to B. To transfer the smaller three-disk tower we use the same strategy recursively.

b)Suppose we want to move a tower of \(n\) disks from the peg labeled X to another peg labeled Y. The third peg labeled Z is assumed to be empty or contain only larger disks. A recursive algorithm can then be formulated as follows:

(image)

c)The recursive implementation in Listing C.16 takes four arguments: the total number of disks numDisks, the number of disks n that should be moved, and the source and destination pegs. We refer to the three pegs using the upper-case letters 'A', 'B', and 'C'. The function returns immediately if the tower is empty or source is equal to destination. Otherwise, the index of the third peg tmp is computed using the following trick:

'A' + 'B' + 'C' - destination - source

This expression uses the fact that the numerical sum of all three peg indexes is always 'A'+'B'+'C'. The index of the largest disk being transferred in each step is numDisks + 1 - n.

Listing C.16ch3โ€ฏ/โ€ฏHanoi

public static void solveHanoiMoves(
        int numDisks, int n, char source, char destination) {
    if (n == 0 || source == destination)
        return;
    int tmp = 'A' + 'B' + 'C' - destination - source;
    solveHanoiMoves(numDisks, n - 1, source, (char) tmp);
    System.out.printf("Move disk %d from %c to %c%n",
            numDisks + 1 - n, source, destination);
    solveHanoiMoves(numDisks, n - 1, (char) tmp, destination);
}

d)Transferring a three-disk tower requires 3 moves, and for a four-disk tower it’s already \(2\cdot 7+1=15\) moves. It’s easy to prove using induction that \(2^n-1\) moves are necessary to move an \(n\)-disk tower. Moving a 64-disk tower therefore requires \(2^{64}-1\) or 18โ€ฏ446โ€ฏ744โ€ฏ073โ€ฏ709โ€ฏ551โ€ฏ615 moves. Even if the priests were able to move one disk per second, transferring the whole tower would take 585 billion years — 42 times the age of the known universe! It’s therefore quite likely that, almost no matter for how many centuries or millennia the priests have already been at work, the world will come to an end long before they are able to move the final disk.

e)The optimal way to reorganize the disks consists of five steps:

B to C, A to C, A to B, C to B, C to A.

The intermediate configurations are ABA, ACA, ACC, BCC, BCB, and BAB.

f)The problem can again be solved recursively. To transform the configuration \(x_0x_1\dots {}x_{n-1}\) into the configuration \(y_0y_1\dots {}y_{n-1}\), first move the \(n-1\) smallest disks out of the way, then move the largest disk from position \(x_0\) to position \(y_0\), and finally move the \(n-1\) smallest disks to their correct positions. More specifically, if \(z\) is the third peg that differs from both \(x_0\) and peg \(y_0\), the steps are as follows:

  • 1. Recursively move \(n-1\) disks from \(x_1 x_2\dots {}x_{n-1}\) to \(zz\dots {}z\).

  • 2. Move a single disk from \(x_0\) to \(y_0\).

  • 3. Recursively move \(n-1\) disks from \(zz\dots {}z\) to \(y_1y_2\dots {}y_{n-1}\).

As a special case, if \(x_0=y_0\), we only have to recursively transform \(x_1\dots {}x_{n-1}\) into \(y_1\dots {}y_{n-1}\). An implementation of this algorithm is shown in Listing C.17. It takes 26 steps to transform BCBAC into CCCCC.

Listing C.17ch3โ€ฏ/โ€ฏHanoi

// Find a sequence of moves that solves the Towers of Hanoi for
// arbitrary start and end states.
public static void solveHanoiPath(String start, String end) {
    int n = start.length();
    if (n == 0)
        return;
    char x0 = start.charAt(0), y0 = end.charAt(0);
    if (x0 == y0) {
        solveHanoiPath(start.substring(1), end.substring(1));
    } else {
        char z = (char) ('A' + 'B' + 'C' - x0 - y0);
        char[] tmp = new char[n - 1];
        for (int i = 0; i < n - 1; i++)
            tmp[i] = z;
        solveHanoiPath(start.substring(1), new String(tmp));
        System.out.println("Move disk from " + x0 + " to " + y0);
        solveHanoiPath(new String(tmp), end.substring(1));
    }
}

Chapter 4

[4.1]

To print the points on the Hilbert curve, the printPoints() method in Listing C.18 starts with a point at the origin \((0,0)\) and repeatedly updates its position using the directions computed by hilbertCurve().

Listing C.18ch4โ€ฏ/โ€ฏHilbertCurve

// Print the coordinates of all points along a Hilbert curve.
private static void printPoints(int order) {
    var directions = new ArrayList<Integer>();
    hilbertCurve(order, NORTH, +1, directions);
    Point p = new Point(0, 0);
    for (int d : directions) {
        System.out.printf("(%d,%d) ", (int) p.x(), (int) p.y());
        p = switch (d) {
            case NORTH -> new Point(p.x(), p.y() + 1);
            case EAST -> new Point(p.x() + 1, p.y());
            case SOUTH -> new Point(p.x(), p.y() - 1);
            case WEST -> new Point(p.x() - 1, p.y());
            default -> throw new RuntimeException(
                    "Invalid direction");
        };
    }
    System.out.printf("(%d,%d)\n", (int) p.x(), (int) p.y());
}

[4.2]

The function describes the line segment between \(\vec {p}_0\) and \(\vec {p}_1\).

[4.4]

To compute the length, we perform the subdivision as usual and then add the length of the resulting line segments (Listing C.19).

Listing C.19ch4โ€ฏ/โ€ฏBezierCurve

// Compute the approximate length of a Bézier curve.
public double length(double tolerance) {
    if (isStraight(tolerance)) {
        return Point.distance(p0, p3);
    } else {
        BezierCurve[] segments = split();
        return segments[0].length(tolerance)
                + segments[1].length(tolerance);
    }
}

[4.5]

The subdivide() method shown in Listing C.20 draws one edge of the Koch snowflake. It takes the end points of a line segment as its input and recursively subdivides it into a fractal curve. We first split the segment between start and end into three equal parts and then erect an equilateral triangle above the two inner points p and q. The formula for the tip of this triangle tip can be derived using basic trigonometry. The resulting four line segments are then subdivided further.

Listing C.20ch4โ€ฏ/โ€ฏKochCurve

// Draw one edge of the Koch snowflake.
public static void subdivide(Point start, Point end, int depth,
        Graphics g) {
    if (depth == 0) {
        g.drawLine((int) start.x(), (int) start.y(),
                (int) end.x(), (int) end.y());
    } else {
        Point p = Point.lerp(start, end, 1.0 / 3.0);
        Point q = Point.lerp(start, end, 2.0 / 3.0);
        Point tip = new Point(
                (q.x() + p.x()) / 2
                        - (q.y() - p.y()) * Math.sqrt(3) / 2,
                (q.y() + p.y()) / 2
                        + (q.x() - p.x()) * Math.sqrt(3) / 2);
        subdivide(start, p, depth - 1, g);
        subdivide(p, tip, depth - 1, g);
        subdivide(tip, q, depth - 1, g);
        subdivide(q, end, depth - 1, g);
    }
}

[4.6]

a)Solving for \(t\) gives

\begin{equation} \label {eq:lineclosest} t_c = \frac {(m_x - a_x)(b_x-a_x) + (m_y - a_y)(b_y-a_y)}{\|\vec {b}-\vec {a}\|^2}. \end{equation}

Therefore, if \(\vec {b}\) doesn’t coincide with \(\vec {a}\), the closest point is

\begin{equation*} \vec {x}_c = \vec {a} + t_c (\vec {b}-\vec {a}). \end{equation*}

b)The implementation of LineSegment is shown in Listing C.21. To implement pointAt(), we use the lerp() function to compute a point between the two end points. To implement closestPoint(), we first determine the parameter of the point closest to m along the curve using closestParam() and then return the point for that parameter. The closestParam() method uses Eq. (C.4) to find the parameter for the closest point along a line and then clamps it to the range \([0,1]\).

Listing C.21ch4โ€ฏ/โ€ฏLineSegment

// A data type for representing line segments in the plane.
public record LineSegment(Point p0, Point p1) {
    public Point pointAt(double t) {
        return Point.lerp(p0, p1, t);
    }

    public double closestParam(Point m) {
        double d = Point.distance(p0, p1);
        if (d == 0.0)
            return 0.0;
        double t = ((m.x() - p0.x()) * (p1.x() - p0.x())
                + (m.y() - p0.y()) * (p1.y() - p0.y()))
                / (d * d);
        return Math.max(0.0f, Math.min(1.0f, t));
    }

    public Point closestPoint(Point m) {
        return pointAt(closestParam(m));
    }
}

c)To find the closest point on a Bézier curve, we apply de Casteljau’s algorithm as shown in Listing C.22. If the current segment is sufficiently straight, we estimate the closest point and its distance from m. Otherwise, we split the segment into two curves, recursively find the closest point on each, and return the point that is closer to m.

Listing C.22ch4โ€ฏ/โ€ฏBezierCurve

public record PointAndDist(Point point, double distance) {
}

// Compute the point on the curve that is closest to 'm'.
public PointAndDist closestPoint(Point m, double tolerance) {
    if (isStraight(tolerance)) {
        double t = new LineSegment(p0(), p3()).closestParam(m);
        Point p = pointAt(t);
        return new PointAndDist(p, Point.distance(p, m));
    } else {
        var segments = split();
        var left = segments[0].closestPoint(m, tolerance);
        var right = segments[1].closestPoint(m, tolerance);
        return left.distance < right.distance ? left : right;
    }
}

[4.7]

a)The constructed point is

\begin{align*} \bigl ((\vec {p}_0+\vec {p}_1)/2 + (\vec {p}_1+\vec {p}_2)/2\bigr )/2 &= (\vec {p}_0/2+\vec {p}_1/2 + \vec {p}_1/2+\vec {p}_2/2)/2\\ &= \vec {p}_0/4+\vec {p}_1/2+\vec {p}_2/4 = \vec {B}(1/2). \end{align*}

b)It’s not hard to prove that the formula for a quadratic Bézier curve simplifies to a line segment if the control point \(\vec {p}_1\) lies halfway between the end points \(\vec {p}_0\) and \(\vec {p}_2\). A simple straightness test is to compare the distance of \(\vec {p}_1\) to the midpoint; this is implemented in isStraight() in Listing C.23.

Listing C.23ch4โ€ฏ/โ€ฏQuadraticBezier

public record QuadraticBezier(Point p0, Point p1, Point p2) {
    private boolean isStraight(double tolerance) {
        return Point.distance(p1, Point.lerp(p0, p2, 0.5))
                < tolerance;
    }

    public void subdivide(double tolerance, List<Point> points) {
        if (isStraight(tolerance))
            points.add(p2);
        Point q0 = Point.lerp(p0, p1, 0.5);
        Point q1 = Point.lerp(p1, p2, 0.5);
        Point s = Point.lerp(q0, q1, 0.5);
        new QuadraticBezier(p0, q0, s).subdivide(tolerance, points);
        new QuadraticBezier(s, q1, p2).subdivide(tolerance, points);
    }
}

JDK: List
•Point: lerp()

c)As indicated in Fig. 4.9, each step of the construction yields one point on the curve and two new control points, one for each half of the original curve. This give us the subdivision scheme implemented by the subdivide() method in Listing C.23.

[4.8]

a)From Eq. (4.2) we have \(\vec {B}(1/2) = (\vec {p}_0 + 3\vec {p}_1 + 3\vec {p}_2 + \vec {p}_3)/8\). The sequence of midpoints computed by de Casteljau’s algorithm computes the same point:

b)If you construct a diagram similar to the one in part (a) but combine adjacent points \(\vec {a}\) and \(\vec {b}\) in each row using linear interpolation \((1-t)\vec {a}+t\vec {b}\), you obtain the formula for Bézier curves Eq. (4.2) on the final line.

c)If we set \(\vec {p}_1=\lerp (\vec {p}_0, \vec {p}_3, 1/3)\) and \(\vec {p}_2=\lerp (\vec {p}_0, \vec {p}_3, 2/3)\) and plug these values into the definition of the Bézier curves, we obtain:

\begin{align*} \vec {B}(t) &= \left [(1-t)^3 + 2t(1-t)^2+t^2(1-t)\right ]\vec {p}_0 \\&\qquad + \left [t(1-t)^2 + 2t^2(1-t)+t^3\right ]\vec {p}_3\\ &= (1-t)[1-t+t]^2\vec {p}_0 + t[t+1-t]^2\vec {p}_3\\ &= (1-t)\vec {p}_0 + t\vec {p}_3. \end{align*} This is the line segment from \(\vec {p}_0\) to \(\vec {p}_3\).

d)According to Eq. (4.2), every point \(\vec {B}(t)\) on the Bézier curve is a linear combination of the four control points

\begin{equation*} \vec {B}(t) = \sum _{k=0}^3w_k \vec {p}_k. \end{equation*}

We therefore have

\begin{equation*} A(\vec {B}(t)) = \vec {A}\sum _{k=0}^3w_k \vec {p}_k + \vec {a} = \sum _{k=0}^3w_k \vec {A}\vec {p}_k + \sum _{k=0}^3w_k\vec {a} = \sum _{k=0}^3w_k (\vec {A}\vec {p}_k + \vec {a}). \end{equation*}

In the second to last step we have used the fact that the weights \(w_k\) sum to 1 (Eq. (4.3)).

[4.9]

a)The five-pointed star can be constructed in two ways, either by joining the sides with single arrows or the sides with double arrows. In the former case the arrows point outwards, in the latter inwards. Placing even two thin rhombs side by side isn’t allowed because there is no way to properly line up the arrow symbols, so there is no way to form a ten-pointed star.

b)Deflating a thick rhomb twice produces three thick rhombs, three thin rhombs, and four halves of a thick rhomb:

c)Listing C.24 defines two functions deflateThin() and deflateThick() that deflate thin and thick triangles, respectively. The functions are mutually recursive since splitting a thin triangle produces a thin and a thick triangle, and splitting a thick triangle produces two thick and a thin triangle.

Listing C.24ch4โ€ฏ/โ€ฏPenrose

static final double phiInv = (Math.sqrt(5) - 1) / 2;

public static void deflateThin(
        int depth, Point p, Point q, Point r,
        List<List<Point>> triangles) {
    if (depth == 0) {
        triangles.add(List.of(r, p, q));
    } else {
        Point a = Point.lerp(p, q, phiInv);
        deflateThin(depth - 1, r, a, q, triangles);
        deflateThick(depth - 1, r, a, p, triangles);
    }
}

public static void deflateThick(
        int depth, Point p, Point q, Point r,
        List<List<Point>> triangles) {
    if (depth == 0) {
        triangles.add(List.of(p, q, r));
    } else {
        Point a = Point.lerp(p, q, phiInv);
        Point b = Point.lerp(p, r, phiInv);
        deflateThick(depth - 1, b, a, p, triangles);
        deflateThin(depth - 1, b, a, q, triangles);
        deflateThick(depth - 1, r, b, q, triangles);
    }
}

JDK: List
•Point: lerp()

The tiling in Fig. 4.10 was constructed by deflating the two triangles of a thick rhomb seven times:

Point p = new Point(0, 0);
Point q = Point.polar(1, 72.0 * Math.PI / 180);
Point r = new Point(1, 0);
Point s = new Point(q.x() + r.x(), q.y() + r.y());
int depth = 1;
List<List<Point>> result = new ArrayList<>();
Penrose.deflateThick(depth, p, r, s, result);
Penrose.deflateThick(depth, p, q, s, result);

If desired, the resulting triangles can be recombined into rhombs.

[4.10]

a)A natural way to model a parametric curve is an interface Curve with a method pointAt() that maps a number t to a Point. We define two additional methods tMin() and tMax(), which return the lower and upper limits of the parameter range. We can then implement the mystery curve as shown in Listing C.26.

Listing C.25ch4โ€ฏ/โ€ฏplotter

public interface Curve {
    Point pointAt(double t);
    double tMin();
    double tMax();
}

Listing C.26ch4โ€ฏ/โ€ฏplotter

public class MysteryCurve implements Curve {
    public Point pointAt(double t) {
        return new Point(
                cos(t) + cos(6 * t) / 2 - sin(-14 * t) / 3,
                sin(t) + sin(6 * t) / 2 + cos(-14 * t) / 3);
    }

    public double tMin() {return 0;}
    public double tMax() {return 2 * Math.PI;}
}

•Curve

b)Figure C.6 shows the result of drawing both curves using 500 line segments each. For the mystery curve this yields a reasonably smooth curve, but since the butterfly curve is significantly more complex, at least twice as many line segments would be necessary.

Figure C.6. Plots of the mystery curve and the butterfly curve

c)As an estimate for the straightness of this segment, we can use the distance between the midpoint along the curve \(\vec {C}((a+b)/2)\) and the midpoint of the two endpoints \((\vec {C}(a)+\vec {C}(b))/2\):

If the distance is less than a given threshold, we consider the segment straight; otherwise, we subdivide it further.

d)One possible program for subdividing arbitrary parametric curves is shown in Listing C.27. To draw a curve, the draw() method first divides the parameter range between tMin() and tMax() into startIntervals pieces of equal size and then calls subdivide() to recursively subdivide each interval. The subdivision process stops if the recursion depth has reached a given upper limit (maxSubdivisionDepth) or if the current segment is sufficiently straight, as measured by a parameter tolerance. The purpose of the maximum subdivision depth is to prevent infinite recursion when plotting pathological curves that consistently fail the straightness test.

Listing C.27ch4โ€ฏ/โ€ฏplotterโ€ฏ/โ€ฏCurvePlotter

// A class for drawing parametric curves using adaptive subdivision.
public class CurvePlotter {
    public int startIntervals = 20;
    public double tolerance = 1e-3;
    public int maxSubdivisionDepth = 10;

    public List<Point> draw(Curve curve) {
        List<Point> points = new ArrayList<>();
        double intervalSize =
                (curve.tMax() - curve.tMin()) / startIntervals;
        for (int i = 0; i < startIntervals; i++) {
            double t0 = curve.tMin() + i * intervalSize;
            double t1 = t0 + intervalSize;
            subdivide(curve, t0, t1,
                    curve.pointAt(t0), curve.pointAt(t1),
                    0, points);
        }
        points.add(curve.pointAt(curve.tMax()));
        return points;
    }

    private void subdivide(Curve curve, double tMin, double tMax,
            Point pMin, Point pMax, int depth, List<Point> points) {
        double tMid = (tMin + tMax) / 2;
        Point mid = curve.pointAt(tMid);
        double d = Point.distance(mid, Point.lerp(pMin, pMax, 0.5));
        if (depth > maxSubdivisionDepth || d < tolerance) {
            points.add(pMin);
        } else {
            subdivide(curve, tMin, tMid, pMin, mid,
                    depth + 1, points);
            subdivide(curve, tMid, tMax, mid, pMax,
                    depth + 1, points);
        }
    }
}

e)The plots in Fig. 4.12 were created using the algorithm discussed in part (d) with a tolerance of 0.003. The same parameters were used for both curves.

Chapter 5

[5.1]

We assume that each long represents one row of the image and that the pixels of each row are stored in the least significant bits. We can then read the bits in each row from left to right and output a sequence of ones and zeros, as shown in Listing C.28.

Listing C.28ch5โ€ฏ/โ€ฏBitmapFont

public static void writePbm(
        long[] image, int width, String fileName)
        throws IOException {
    try (var out = new PrintWriter(fileName)) {
        out.println("P1");
        out.printf("%d %d\n", width, image.length);
        for (long row : image) {
            long mask = 1L << (width - 1);
            for (int i = 0; i < width; i++) {
                out.print((row & mask) != 0 ? "1 " : "0 ");
                mask >>>= 1;
            }
            out.println();
        }
    }
}

[5.2]

For left rotations we append the highest \(n\) bits to the lowest \(32-n\) bits, and for right rotations we append the highest \(32-n\) bits to the lowest \(n\) bits:

public static int rotl(int value, int n) {
    return (value << n) | (value >>> (32 - n));
}

public static int rotr(int value, int n) {
    return (value >>> n) | (value << (32 - n));
}

[5.3]

The resulting images look as follows:

(math image)

[5.4]

First swap the two 16-bit halves and then exchange the bytes in each half:

static int reverseBytes(int value) {
    int tmp = (value << 16) | (value >>> 16);
    return ((tmp >>> 8) & 0x00ff00ff) | ((tmp & 0x00ff00ff) << 8);
}

[5.5]

The bit pattern of \(-1\) is obtained by converting the number \(2^w + (-1)=2^w-1\) to binary; the binary representation of this number always consists of \(w\) ones.

[5.6]

With ten bits we can store numbers between \(-512\) and \(511\), inclusively. Here is the completed table:

.
number bit pattern
0 0000000000
\(-1\) 1111111111
\(489\) 0111101001
\(-384\) 1010000000
\(-417\) 1001011111
\(231\) 0011100111

[5.7]

The expression computes \(2x+1\) and works for all integers \(x\), provided \(2x+1\) doesn’t overflow. This is easy to see: For every even number in two’s-complement representation, setting the least significant bit is equivalent to incrementing the number by 1. (Of course, there are is no reason to prefer this solution to 2*x + 1 in practice.)

[5.8]

The expression -1 >> k is always \(\lfloor -1/2^k\rfloor =-1\), and the resulting bit pattern consists of 32 ones. The expression -1 >>> k produces a bit pattern that consists of \(32-k\) ones.

[5.9]

The sum is an expansion of the binary representation of the multiplier, so there is one term for each 1 in \(1111_2=15\).

It is sometimes possible to reduce the number of operations even further by factorizing the multiplier appropriately. For instance, we can rewrite \(15x\) as \(5\cdot (3\cdot x)\) to save one addition:

t = (x << 1) + x
r = (t << 2) + (t << 1)

A similar technique can be used to speed up the computation of integer powers; see [60, Section 4.6.3].

[5.10]

It’s an alternative way of testing whether s is a subset of t.

[5.11]

The XOR operator returns the bits that are contained in exactly one of its two arguments. This operation is also known as the symmetric difference of two sets, which is usually denoted by the \(\triangle \) operator:

\begin{equation*} \{1, 4, 7\} \mathbin {\triangle } \{0, 5, 7\} = \{1, 4, 5\} \end{equation*}

[5.12]

If \(n=0\), there is no least significant bit that could be cleared, which is consistent with the result \(n\AND (n-1) = 0 \AND -1 =0\). If \(n\not =0\), we can write its bit pattern in the form \(\alpha 10^k\), where the single 1 denotes the least significant 1-bit, \(0^k\) the sequence of \(k\) zeros in the lowest bits of \(n\), and \(\alpha \) the most significant bits of \(n\), which we don’t care about. In two’s-complement representation, the bit pattern of \(n-1\) is \(\alpha 01^k\), both for positive and negative integers, so we have

\begin{equation*} n \AND (n-1) = \alpha 10^k \AND \alpha 01^k = \alpha 0^{k+1}, \end{equation*}

which is the bit pattern of \(n\) with the least significant bit turned off. This argument also works for the smallest negative number \(n=-2^{w-1}\), where \(w\) is the bit-width. In this case, subtracting 1 from \(n\) overflows and produces the largest positive number \(n-1=2^{w-1}-1\),

[5.13]

We can find the number of 1-bits in \(n\) by repeatedly clearing the least significant bit of \(n\) and counting the number of iterations required until \(n=0\) (Listing C.29). This algorithm for counting bits is known as Kernighan’s algorithm:1

Listing C.29ch5โ€ฏ/โ€ฏBitCount

// Kernighan's algorithm for counting bits.
public static int bitCountKernighan(long value) {
    int count = 0;
    while (value != 0) {
        value &= value - 1;
        count++;
    }
    return count;
}

[5.14]

All powers of 2 have just a single bit set, so we can simple clear the least significant bit and check whether the result is 0:

public static boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}

The simpler test (n & (n - 1)) == 0 is almost correct but fails for \(n=0\). Alternatively, we can check if the number is positive and has exactly one bit set:

public static boolean isPowerOfTwo(int n) {
   return n > 0 && Integer.bitCount(n) == 1;
}

[5.15]

a)The rule produces a checkerboard pattern.

b)Since \(00110010_2=50\), it’s rule 50.

c)We can store the current state of all cells as an array of integers cells: the \(k\)th cell is active if cells[k] is 1 and inactive if it is 0. Listing C.30 demonstrates how to compute the next generation of cells: We read the state of each cell and its two neighbors and compute its new state using nextState(). Computing the next state is easy once you understand how the numbering scheme for rules works. Given the rule’s number \(r\) and the current state of the cell and its neighbors \(c_0\), \(c_1\), and \(c_2\), the new state of the cell is simply the binary digit of \(r\) at position \((c_0c_1c_2)_2\).

Listing C.30ch5โ€ฏ/โ€ฏCellular1D

// Evolve an array of elementary cellular automata.
public static void evolveCells(int rule, int[] cells, int[] next) {
    for (int k = 0; k < cells.length; k++) {
        int c0 = cells[k == 0 ? cells.length - 1 : k - 1];
        int c1 = cells[k];
        int c2 = cells[k == cells.length - 1 ? 0 : k + 1];
        next[k] = nextState(c0, c1, c2, rule);
    }
}

static int nextState(int c0, int c1, int c2, int rule) {
    int neighborhood = (c0 << 2) | (c1 << 1) | c2;
    return (rule & (1 << neighborhood)) != 0 ? 1 : 0;
}

d)Figures C.7 and C.8 show the evolution of rules 0 to 31 for two configurations of cells. In the first image, the top row contains exactly one active cell in the middle, whereas in the second image the top contains a random selection of active cells. Many rules eventually lead to a stable state in which each row is a (shifted) copy of a previous row, but a few rules produce fractal or chaotic patterns, including rules 18, 22, 26, and 30.

(-tikz- diagram)

Figure C.7. Evolution of the first 32 elementary cellular automata.

(-tikz- diagram)

Figure C.8. Evolution of the first 32 elementary cellular automata with random cells in the first generation.

[5.16]

a)All operations on an individual number \(k\) require us to locate the corresponding bit in bits[]. The “address” of \(k\) has two parts: the index of the long integer inside bits[], which is computed by dividing \(k\) by 64 (or by using an equivalent right-shift), and the bit index of the bit inside bits[index], which is the remainder of dividing \(k\) by 64. If index is larger than the current size of bits[] we have to reallocate the array (Listing C.31).

Listing C.31ch5โ€ฏ/โ€ฏBitSet

// Add a nonnegative number to the bit set.
public boolean add(int value) {
    if (value < 0)
        throw new IllegalArgumentException("Negative value");
    int index = value >> 6;
    long mask = 1L << (value & 0x3f);
    if (index >= bits.length)
        bits = Arrays.copyOf(bits, index + 1);
    long oldValue = bits[index];
    bits[index] |= mask;
    return oldValue != bits[index];
}

b)For numbers outside the allowed range, the contains() and remove() methods in Listing C.32 do nothing and simply return false. For all other values, contains() checks the correspondng bit, and remove() sets it to 0.

Listing C.32ch5โ€ฏ/โ€ฏBitSet

// Check whether 'value' is contained in the set.
public boolean contains(int value) {
    int index = value >> 6;
    long mask = 1L << (value & 0x3f);
    return value >= 0 && index < bits.length
            && (bits[index] & mask) != 0;
}

// Remove 'value' from the set.
public boolean remove(int value) {
    int index = value >> 6;
    long mask = 1L << (value & 0x3f);
    if (value >= 0 && index < bits.length) {
        long oldValue = bits[index];
        bits[index] &= ~mask;
        return oldValue != bits[index];
    }
    return false;
}

•BitSet

c)The two constructors are shown in Listing C.33. The first one copies the given bit set by searching for the first nonzero entry in its bits[] array and then use Arrays.copyOf() to create an appropriately sized copy. The other constructor simply iterates over the integers in the collection and adds them to the bit set.

Listing C.33ch5โ€ฏ/โ€ฏBitSet

public BitSet(BitSet other) {
    int n = other.bits.length;
    while (n > 0 && other.bits[n - 1] == 0)
        n--;
    bits = Arrays.copyOf(other.bits, n);
}

public BitSet(Collection<Integer> c) {
    for (int v : c)
        add(v);
}

d)The implementations of equals() and hashCode() are shown in Listing C.34. A bit set is considered equal to another object o if o is of type BitSet and both bit sets that have 1-bits at the same positions. To compare the 1-bits, we first check that the smaller of the two bits[] arrays is equal to the first part of the larger array and then verify that the larger array doesn’t contain any additional 1-bits. To compute the hash code of a bit set, we hash the contents of the bits[] array. We iterate over the array from right to left to ensure that the hash code isn’t affected by trailing zeros in bits[].

Listing C.34ch5โ€ฏ/โ€ฏBitSet

public boolean equals(Object o) {
    if (!(o instanceof BitSet other))
        return false;
    int n = Math.min(bits.length, other.bits.length);
    if (!Arrays.equals(bits, 0, n, other.bits, 0, n))
        return false;
    long[] rest = bits.length > n ? bits : other.bits;
    for (int i = n; i < rest.length; i++) {
        if (rest[i] != 0)
            return false;
    }
    return true;
}

public int hashCode() {
    int h = 0;
    for (int i = bits.length - 1; i >= 0; i--)
        h = h * 31 + Long.hashCode(bits[i]);
    return h;
}

•BitSet

e)For the implementation of size(), we iterate over all elements of bits[] and use Long.bitCount() to count all 1-bits. For isEmpty(), we search for any nonzero entry in bits[].

Listing C.35ch5โ€ฏ/โ€ฏBitSet

public int size() {
    int count = 0;
    for (long b : bits)
        count += Long.bitCount(b);
    return count;
}
public boolean isEmpty() {
    for (long b : bits) {
        if (b != 0)
            return false;
    }
    return true;
}

JDK: Long
•BitSet

f)To implement the four set operations, we have to iterate over the bits of both bit sets and use the correspondences in Fig. 5.7. The main complication is that the bits arrays can differ in size. As in the implementation of equals(), we therefore split each function into two parts: The first part iterates over the common array entries and the second handles entries that exist only in the larger array. Listing C.36 demonstrates how to do this for containsAll(); the other three methods are implemented similarly.

Listing C.36ch5โ€ฏ/โ€ฏBitSet

public boolean containsAll(BitSet other) {
    int n = Math.min(bits.length, other.bits.length);
    for (int i = 0; i < n; i++) {
        long a = bits[i], b = other.bits[i];
        if ((a & b) != b)
            return false;
    }
    for (int i = bits.length; i < other.bits.length; i++) {
        if (other.bits[i] != 0)
            return false;
    }
    return true;
}

// The implementations of addAll(), removeAll(), and retainAll()
// are similar and have been omitted.

•BitSet

g)The iterator for BitSet resembles the BitIterator class discussed in Section 5.5. The main difference is that we now iterate over an array of long integers and therefore have to keep track of the current position index inside this array (Listing C.37). The constructor Iter() initializes index and currentBits by searching the elements of bits[] for the first nonzero entry.

Listing C.37ch5โ€ฏ/โ€ฏBitSet.Iter

// Internal iterator class for BitSet.
private class Iter implements Iterator<Integer> {
    int index = -1;  // current position in BitSet.bits[]
    long currentBits = 0;  // remaining bits at current position
    int lastValue = -1;  // last value returned by next()

    Iter() {
        while (currentBits == 0 && index < bits.length - 1)
            currentBits = bits[++index];
    }

    @Override
    public boolean hasNext() {return currentBits != 0;}

    @Override
    public Integer next() {
        lastValue =
                (index << 6) + Long.numberOfTrailingZeros(currentBits);
        currentBits &= currentBits - 1;
        while (currentBits == 0 && index < bits.length - 1)
            currentBits = bits[++index];
        return lastValue;
    }

    @Override
    public void remove() {BitSet.this.remove(lastValue);}
}

// Return an iterator that iterates over the numbers in this bit set.
@Override
public Iterator<Integer> iterator() {return new Iter();}

The remaining members of Iter implement the three methods of the Iterator interface: hasNext() checks whether the last bit has been reached, which in our case is only the case if currentBits is zero; next() computes the position of the current bit, which is obtained by adding the position of the least significant bit in currentBits to \(64\cdot \mathtt {index}\), and then advances the iterator by adjusting currentBits and index. Finally, the remove() method removes the last value returned by next() from the bit set.

[5.17]

Listing C.38 demonstrates how to count the bits in a 64-bit integer by repeatedly adding adjacent groups of bits.

Listing C.38ch5โ€ฏ/โ€ฏBitCount

// Count bits using a divide-and-conquer scheme.
public static int bitCountSubdivide(long n) {
    n = (n & 0x5555555555555555L)
            + ((n >> 1) & 0x5555555555555555L);
    n = (n & 0x3333333333333333L)
            + ((n >> 2) & 0x3333333333333333L);
    n = (n & 0x0f0f0f0f0f0f0f0fL)
            + ((n >> 4) & 0x0f0f0f0f0f0f0f0fL);
    n = (n & 0x00ff00ff00ff00ffL)
            + ((n >> 8) & 0x00ff00ff00ff00ffL);
    n = (n & 0x0000ffff0000ffffL)
            + ((n >> 16) & 0x0000ffff0000ffffL);
    n = (n & 0x00000000ffffffffL)
            + ((n >> 32) & 0x00000000ffffffffL);
    return (int) n;
}

[5.18]

a)There are two 1-bit numbers, \(0_2\) and \(1_2\). The number of trailing zeros of \(0_2\) is 1 and the number of trailing zeros of \(1_2\) is 0, so we have

\begin{equation*} \text {ntz}(1, v) = 1-v. \end{equation*}

b)The implementation in Listing C.39 expands the recursive function calls and eliminates the final call to \(\text {ntz}(1, v)\) by handling the case value == 0 at the start of the function. This implementation can be sped up even further by replacing the last three if statements with a lookup table.

Listing C.39ch5โ€ฏ/โ€ฏTrailingZeros

// Count the number of trailing zeros using a form of binary search.
public static int countTrailingZeros(long value) {
    if (value == 0)
        return 64;
    int count = 0;
    if ((value & 0xffffffffL) == 0) {
        value >>>= 32;
        count += 32;
    }
    if ((value & 0xffffL) == 0) {
        value >>>= 16;
        count += 16;
    }
    if ((value & 0xffL) == 0) {
        value >>>= 8;
        count += 8;
    }
    if ((value & 0xfL) == 0) {
        value >>>= 4;
        count += 4;
    }
    if ((value & 0x3L) == 0) {
        value >>>= 2;
        count += 2;
    }
    if ((value & 0x1L) == 0)
        count += 1;
    return count;
}

c)We use a similar expression as in the case of the \(\text {ntz}\) function:

\begin{equation} \label {eq:nlz64} \text {nlz}(64, v) = \begin{cases} 32+\text {nlz}(32, v) & \text {if the upper 32~bits of $v$ are zero};\\ \text {nlz}(32, v \shr 32) & \text {otherwise}. \end {cases} \end{equation}

d)In this case, getting rid of the recursion is slightly more difficult because there is no obvious way to replace the two occurrences of nlz in Eq. (C.5) with a single function call. The trick is to rewrite the literal translation

if ((v & ~0xffffffff) == 0) {
    return 32 + nlz(32, v)
} else {
    return nlz(32, v >>> 32);
}

as

int count = 32;
if ((v & ~0xffffffff) != 0) {
    count -= 32;
    v >>>= 32;
}
return count + nlz(32, v)

and then expand nlz(32, v) in the same way. This gives us the implementation shown in Listing C.40.

Listing C.40ch5โ€ฏ/โ€ฏLeadingZeros

// Count the number of trailing zeros using a form of binary search.
public static int countLeadingZeros(long value) {
    if (value == 0)
        return 64;
    int count = 63;
    if ((value & ~0xffffffffL) != 0) {
        value >>>= 32;
        count -= 32;
    }
    if ((value & ~0xffffL) != 0) {
        value >>>= 16;
        count -= 16;
    }
    if ((value & ~0xffL) != 0) {
        value >>>= 8;
        count -= 8;
    }
    if ((value & ~0xfL) != 0) {
        value >>>= 4;
        count -= 4;
    }
    if ((value & ~0x3L) != 0) {
        value >>>= 2;
        count -= 2;
    }
    if ((value & ~0x1L) != 0)
        count -= 1;
    return count;
}

1 The algorithm is named after Brian W. Kernighan who popularized it in [58]. The technique was first described by Peter Wegner in [95].

Chapter 6

[6.1]

It computes the set of all holes that can be reached by moving any of the pegs on board.

[6.2]

Consider all eight possible assignments of three bits and verify that the expressions on either side of the equation produce the same result:

\begin{equation*} \begin{array}{c@{}c@{}ccccc} A & B & C & A\AND (B\OR C) & (A\AND B)\OR (A\AND C) & A\OR (B\AND C)&(A\OR B)\AND (A\OR C)\\ \hline 0 & 0 & 0 & 0\AND 0 = 0 & 0\OR 0=0 & 0 \OR 0=0 & 0\AND 0=0 \\ 0 & 0 & 1 & 0\AND 1 = 0 & 0\OR 0=0 & 0 \OR 0=0 & 0\AND 1=0 \\ 0 & 1 & 0 & 0\AND 1 = 0 & 0\OR 0=0 & 0 \OR 0=0 & 1\AND 0=0 \\ 0 & 1 & 1 & 0\AND 1 = 0 & 0\OR 0=0 & 0 \OR 1=1 & 1\AND 1=1 \\ 1 & 0 & 0 & 1\AND 0 = 0 & 0\OR 0=0 & 1 \OR 0=1 & 1\AND 1=1 \\ 1 & 0 & 1 & 1\AND 1 = 1 & 0\OR 1=1 & 1 \OR 0=1 & 1\AND 1=1 \\ 1 & 1 & 0 & 1\AND 1 = 1 & 1\OR 0=1 & 1 \OR 0=1 & 1\AND 1=1 \\ 1 & 1 & 0 & 1\AND 1 = 1 & 1\OR 1=1 & 1 \OR 1=1 & 1\AND 1=1 \end {array} \end{equation*}

The same laws must hold for sequences of bits since the bit operators \(\AND \) and \(\OR \) operate element-wise.

[6.3]

b)With the numbering scheme shown in Fig. C.9, the offsets between neighboring cells are constant and it becomes possible to use bitboards and the techniques discussed in the text to compute possible jumps.

Figure C.9. Numbering scheme for triangular peg solitaire

[6.4]

The problem can be represented using one bitboard for each player. Some bit operations become easier if we add an empty column to the board, so we will use bitboards of size \(8\times 6\), which easily fit into long integers. The variable BOARD_MASK in Listing C.41 selects the bits of the board proper, without the empty column on the left.

Listing C.41ch6โ€ฏ/โ€ฏConnect4

static int WIDTH = 7, HEIGHT = 6;

// Bit board of size (WIDTH + 1) x HEIGHT
static long BOARD_MASK
        = 0b01111111_01111111_01111111_01111111_01111111_01111111L;
//          row 1    row 2    row 3    row 4    row 5    row 6
// bits:   47..40   39..32   31..24   23..16    15..8    7..0

Adjacent squares on the board are separated by a constant offset on the bitboard:

.
direction left right down up up+left up+right
offset \(+1\) \(-1\) \(+8\) \(-8\) \(+9\) \(+7\)

We can therefore use bit shifts to move the entire board in a certain direction. The added empty column serves as a buffer that prevents bit shifts from moving tokens to the opposite side of the board.

The fourBitsSet() function in Listing C.42 checks whether there are four bits with a certain offset from each other on a given board; notice how BOARD_MASK is used to clear the extra column after every shift. The checkWin() method in the same listing now identifies a winning position by checking for a line of four tokens in all four directions: horizontal, vertical, and the two diagonals.

Listing C.42ch6โ€ฏ/โ€ฏConnect4

// Check whether the board contains a sequence of four bits at a
// certain offset.
static boolean fourBitsSet(long board, int offset) {
    long step1 = (board >>> offset) & BOARD_MASK;
    long step2 = (step1 >>> offset) & BOARD_MASK;
    long step3 = (step2 >>> offset) & BOARD_MASK;
    return (board & step1 & step2 & step3) != 0;
}

// Check whether there is a line of four adjacent tokens
// anywhere on the bitboard.
static boolean checkWin(long board) {
    int leftOffset = 1;
    int upOffset = WIDTH + 1;
    int upLeftOffset = WIDTH + 1 + 1;
    int upRightOffset = WIDTH + 1 - 1;
    return fourBitsSet(board, leftOffset)
            || fourBitsSet(board, upOffset)
            || fourBitsSet(board, upLeftOffset)
            || fourBitsSet(board, upRightOffset);
}

•Connect4: BOARD_MASK, HEIGHT, WIDTH

[6.5]

We can obtain a rough estimate by timing how long it takes the program in Listing 6.5 to generate a few thousand solutions and then extrapolating the result to 41 quadrillion possible solutions. On the author’s machine, generating 10โ€ฏ000 solutions without printing them takes 27 seconds, which gives us an estimate of

\begin{equation*} \frac {40\,861\,647\,040\,079\,968}{10\,000\cdot 60\cdot 60\cdot 24\cdot 365}\times 27\,\text {s}\approx 349\,843\,\text {years} \end{equation*}

to generate all solutions.

[6.6]

After the algorithm has completed, there are 23โ€ฏ475โ€ฏ687 entries in numSolutions, which is the number of visited boards. Only 1โ€ฏ679โ€ฏ071 of those entries have a nonzero count associated with them, so only approximately 7โ€ฏ% of all reachable boards are actually solvable. This explains why humans find peg solitaire moderately difficult, despite there being quadrillions of possible solutions.

[6.7]

The implementation in Listing C.43 stores previously computed values of the Fibonacci sequence in an array fibArray. The value 0 indicates an unknown value.

Listing C.43ch6โ€ฏ/โ€ฏFibMemoize

private static int[] fibArray = {1, 1};

public static int fib(int n) {
    if (n >= fibArray.length)
        fibArray = Arrays.copyOf(fibArray, n + 1);
    if (fibArray[n] == 0)
        fibArray[n] = fib(n - 1) + fib(n - 2);
    return fibArray[n];
}

JDK: Arrays

[6.8]

The Memoizer class shown in Listing C.44 implements the same interface as the function func it wraps. To cache previous return values of func, we use a hash table that is queried and updated every time the apply() method is called.

Listing C.44ch6โ€ฏ/โ€ฏMemoizer

public class Memoizer<T, R> implements Function<T, R> {
    private final Function<T, R> func;
    private final HashMap<T, R> cache = new HashMap<>();

    public Memoizer(Function<T, R> func) {
        this.func = func;
    }

    public R apply(T t) {
        return cache.computeIfAbsent(t, func);
    }
}

[6.9]

a)The outcomes for a few small values of \(n\) and \(m\) are shown in Table C.1. For \(1,1\)-Nim, the first player always loses. For \(1,m\)-Nim with \(m>1\), the first player wins by removing \(m-1\) coins from the second pile. For \(2,2\)-Nim, the first player loses since all moves lead to a winning state for the opponent, but for \(2,m\)-Nim with \(m>2\) the first player wins by taking \(m-2\) coins from the second pile. The same pattern repeats for \(n,m\)-Nim in general: The first player wins if \(n\ne m\) but loses if \(n=m\), because in this case every possible move leads to a winning position for the opponent.

Table C.1 Winning strategies for \(n,m\)-Nim
.
\(n\) \(m\) Outcome Winning move
1 1 loss –
1 \(> 1\) win Take \(m-1\) coins
2 2 loss –
2 \(>2\) win Take \(m-2\) coins
3 3 loss –
3 \(>3\) win Take \(m-3\) coins

b)The detailed evaluation is fairly complex, but we can use the symmetry of \(W\) and a few logical shortcuts to simplify the computation:

\begin{align*} W(1,1,2) &= \neg W(0,1,2) \lor \neg W(1,0,2) \lor \neg W(1,1,1) \lor \neg W(1,1,0)\\ &= \neg W(0,1,2) \lor \neg W(1,1,1) \lor \neg W(1,1,0) \tag {1}\\ &= \neg W(0,1,2) \lor W(1,1,0) \lor \neg W(1,1,0) \tag {2}\\ &= \mathsf {T} \tag {3} \end{align*} (1) follows from the fact that \(W\) is symmetric, so \(W(1,0,2) = W(0,1,2)\); (2) from \(W(1,1,1)=\neg W(1,1,0)\); and (3) from the fact that \(\neg X\lor X=\mathsf {T}\) for all \(X\).

c)We can represent each position as a list of integers that holds the number of coins in each pile. The goal is to implement a program that maps such a list to a Boolean value that indicates whether the corresponding position is winnable.

We use memoization to remember all previously computed values of this mapping in a hash table called winningCache; see Listing C.45. The constructor NimMemoize() initializes this table by mapping the empty list to false: The state with no coins left is by definition a losing position.

Listing C.45ch6โ€ฏ/โ€ฏNimMemoize

public class NimMemoize {
    private final Map<List<Integer>, Boolean> winningCache;

    public NimMemoize() {
        winningCache = new HashMap<>();
        // The empty list (no coins) is a losing position
        winningCache.put(List.of(), false);
    }

    public static List<Integer> normalize(List<Integer> piles) {
        var newPiles = new ArrayList<>(piles);
        newPiles.sort(Integer::compare);
        newPiles.removeIf(k -> k == 0);
        return newPiles;
    }

    // Determine whether 'piles' is a winning position.
    public boolean isWinning(List<Integer> piles) {
        piles = normalize(piles);
        if (winningCache.containsKey(piles))
            return winningCache.get(piles);
        for (int h = 0; h < piles.size(); h++) {
            for (int n = 1; n <= piles.get(h); n++) {
                var newPiles = new ArrayList<>(piles);
                newPiles.set(h, piles.get(h) - n);
                if (!isWinning(newPiles)) {
                    winningCache.put(piles, true);
                    return true;
                }
            }
        }
        winningCache.put(piles, false);
        return false;
    }
}

The normalize() method is used to map all equivalent positions to a single unique representative. Since empty piles can be ignored and the order of piles doesn’t matter, we can normalize a game state by sorting the piles by size and keeping only nonzero entries. The function isWinning() in Listing C.45 checks whether removing \(n\) coins from the \(k\)th pile produces a position that is unwinnable for the opponent. We memoize previous results in the hash table winningCache.

Calling this function tells us that the position \(10,5,4,3\) is winnable.

d)The Nim sum of \((2,5,6)\) is

\begin{equation*} \begin{array}{ccc@{\extracolsep {1cm}}l} 0 & 1 & 0 & =2\\ 1 & 0 & 1 & =5\\ 1 & 1 & 0 & =6\\ \midrule 0 & 0 & 1 & \text {Sum, ignoring carries}\\ \end {array} \end{equation*}

The result is nonzero, so this is a winning position. Only the last bit changes for \((2,5,7)\), which is therefore a losing position.

e)To find all possible winning moves, we first compute the Nim sum of the position. We then check for each pile of coins whether there is a positive number of coins n whose removal would reduce the Nim sum to zero, which indicates a losing position for the opponent. The printWinningMoves() function in Listing C.46 implements this algorithm. The winning moves for \((3,6,6)\) are:

- take 3 coin(s) from pile 0
- take 1 coin(s) from pile 1
- take 1 coin(s) from pile 2

Listing C.46ch6โ€ฏ/โ€ฏNim

static void printWinningMoves(List<Integer> piles) {
    int nimSum = 0;
    for (int pile : piles)
        nimSum ^= pile;
    System.out.printf("Winning moves for %s:%n", piles);
    for (int pile = 0; pile < piles.size(); pile++) {
        int n = piles.get(pile) - (piles.get(pile) ^ nimSum);
        if (n > 0) {
            System.out.printf(
                    "- take %d coin(s) from pile %d%n", n, pile);
        }
    }
}

JDK: System

[6.10]

b)To represent the Sudoku board, we use an array of \(9\times 9\) integers in which empty squares are marked using the number 0 (Listing C.47). In addition, we use a handful of bit sets to keep track of which digits can still be placed in each of the 9 rows (rowOptions), columns (colOptions), and \(3\times 3\) blocks (boxOptions). (The bit sets are stored in integers of type long instead of int to make it easier to use the utility functions we defined in Chapter 5.) The putDigit() method writes a digit to the specified square on the board and then removes it from the pool of available digits by modifying the corresponding bit sets. The removeDigit() method undoes this action.

Listing C.47ch6โ€ฏ/โ€ฏSudoku

public class Sudoku {
    private int[][] board = new int[9][9];
    private long[] rowOptions = new long[9];
    private long[] colOptions = new long[9];
    private long[] boxOptions = new long[9];

    static int blockIndex(int row, int col) {
        return 3 * (row / 3) + col / 3;
    }

    void putDigit(int row, int col, int digit) {
        this.board[row][col] = digit;
        rowOptions[row] &= ~Bits.bit(digit);
        colOptions[col] &= ~Bits.bit(digit);
        boxOptions[blockIndex(row, col)] &= ~Bits.bit(digit);
    }

    void removeDigit(int row, int col, int digit) {
        board[row][col] = 0;
        rowOptions[row] |= Bits.bit(digit);
        colOptions[col] |= Bits.bit(digit);
        boxOptions[blockIndex(row, col)] |= Bits.bit(digit);
    }

    public Sudoku(String[] board) {
        long ALL_DIGITS = Bits.bits(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Arrays.fill(rowOptions, ALL_DIGITS);
        Arrays.fill(colOptions, ALL_DIGITS);
        Arrays.fill(boxOptions, ALL_DIGITS);
        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                if (!Character.isDigit(board[row].charAt(col)))
                    continue;
                int digit = board[row].charAt(col) - '0';
                if (digit != 0)
                    putDigit(row, col, digit);
            }
        }
    }

    // ...
}

•Bits: bit()

The final method in Listing C.47 is the constructor Sudoku(), which uses an array of Strings to initialize the board. Each entry of board describes one row of the board. For example, the board in Fig. 6.7 is encoded as follows:

String[] board = {
        "000000308", "027100060", "004002001",
        "080540009", "750900000", "000010080",
        "006000050", "408009000", "000000040"
};

The solve() method in Listing C.48 attempts to solve a given board using backtracking. The function first searches for the next empty square on the board (row and col) and then tries all valid digits for this square; the set of valid digits is obtained by intersecting the corresponding bit sets in rowOptions, colOptions, and boxOptions. For each possible digit, solve() calls itself recursively to complete the solution.

Listing C.48ch6โ€ฏ/โ€ฏSudoku

public String solve() {
    // Find first row with empty squares
    int row = 0;
    while (row < 9 && rowOptions[row] == 0)
        row++;
    if (row >= 9) {
        // Solution found
        var sb = new StringBuilder();
        for (int[] r : board)
            sb.append(Arrays.toString(r)).append('\n');
        return sb.toString();
    } else {
        // Find first empty column
        int col = 0;
        while (col < 9 && board[row][col] != 0)
            col++;
        // Recursively try all allowed digits.
        long validDigits = rowOptions[row] & colOptions[col]
                & boxOptions[blockIndex(row, col)];
        for (int digit : Bits.iterate(validDigits)) {
            putDigit(row, col, digit);
            var solution = solve();
            if (solution != null)
                return solution;
            removeDigit(row, col, digit);
        }
    }
    return null;
}

Chapter 7

[7.1]

The normal rules for computing neighbors can be used for the interior nodes. Every interior node has exactly six neighbors but no incoming edges. In graph theory, a node with no incoming edges is called a source, so all these nodes are sources.

[7.2]

The graph looks as follows:

One Hamiltonian cycle is \(00\to {}20\to {}11\to {}21\to {}01\to {}10\to {}00\).

[7.3]

True. There is always a layer at distance 0 that contains just the starting node.

[7.4]

Due to the symmetry of the graph, there are just four different eccentricities:

\begin{equation*} \begin{array}{cc} n & \epsilon (n)\\ 00,03,50,53& 7\\ 20,23,30,33& 6\\ 01,02,51,52& 5\\ 10,13,40,43& 4 \end {array} \end{equation*}

[7.5]

The implementation of printNodes() in Listing C.49 collects the string representation of every node on the path and then joins them into a single string.

Listing C.49ch7โ€ฏ/โ€ฏPath

default String printNodes() {
    var nodeNames = new ArrayList<String>();
    for (N node : toNodeList())
        nodeNames.add(node.toString());
    return String.join(" -> ", nodeNames);
}

[7.6]

a)The problem has two solutions that differ in whether the wolf or the cabbage is transferred in the second step:

  • 1. Move the goat to the other shore.

  • 2a. Move the wolf and take the goat back on the return trip. Then move the cabbage.

  • 2b. Move the cabbage and take the goat back on the return trip. Then move the wolf.

  • 3. Move the goat.

b)If we represent this side of the river by 0 and the other side by 1, we can encode the current positions of the wolf, the goat, and the cabbage as a sequence of three digits \(wgc\). There are obviously 8 such states. (The farmer’s position simply alternates between the two sides of the river and is therefore redundant.) We start in the \(000\) state in which the entire party is on this side of the river, and the goal is to transition to the \(111\) state where everyone is on the other side. Every time the farmer ferries one party member across the river, the corresponding digit flips from 0 to 1 or vice versa.

c)Here is an image of the graph corresponding to the wolf-goat-cabbage problem:

If you mirror the graph vertically or horizontally, you obtain the same graph with different labels. The left-right symmetry reflects the fact that it doesn’t matter how we label the banks of the river, and the up-down symmetry the fact that the wolf and the cabbage constrain the problem in the same way: They both cannot be left alone with the goat.

There are two different paths of length 5 from the start 000 to the destination 111, one moving along the top of the graph and the other along the bottom:

\begin{align*} & 000\to {}010\to {}110\to {}100\to {}101\to {}111 && \text {upper path}\\ & 000\to {}010\to {}011\to {}001\to {}101\to {}111 && \text {lower path} \end{align*} The two paths differ mainly in whether the farmer takes the wolf or the cabbage on the second trip.

d)If we are currently in a state \(wgc\), the next state is either \((1-w)gc\), \(w(1-g)c\), or \(wg(1-c)\). The wolf’s digit may only be flipped if the goat and the cabbage are currently on different sides of the river, in other words if \(g\ne c\), and for a similar reason, the cabbage digit may only be flipped if \(w\ne g\); only the goat digit may be flipped at any time, regardless of the other digits. We can therefore transition to a neighboring state under the following conditions:

\begin{equation} \label {eq:wgc} \begin{array}{@{}cc} \text {\emph {neighbor state}} & \text {\emph {condition}}\\ (1-w)gc & g\ne c\\ w(1-g)c & \\ wg(1-c) & w\ne g\\ \end {array} \end{equation}

For instance, in the starting state \(000\), we have both \(g=c\) and \(w=g\), so the first and last conditions are not satisfied and only the goat can be transferred to the other side of the river, which gives us the new state \(010\). For this new state, we have \(g\ne c\) and \(w\ne g\), so we can transition into all three neighboring states \(110\), \(000\), and \(011\). Notice that the second transition leads us back to the original state, which corresponds to the fact that the farmer can always undo her last move.

We can represent each node in the wolf-goat-cabbage graph as a String of binary digits and the entire graph as a class that implements Graph (Listing C.50). In this implementation, the nodes() method returns a precomputed list of the graph’s eight nodes and neighbors() implements Eq. (C.6). The helper method flipDigit() computes the label of a neighboring node by changing the digit at the specified index from 0 to 1 and vice versa.

Listing C.50ch7โ€ฏ/โ€ฏWolfGoatCabbageGraph

public class WolfGoatCabbageGraph implements Graph<String> {
    public List<String> nodes() {
        return List.of("000", "001", "010", "011",
                "100", "101", "110", "111");
    }

    public List<String> neighbors(String state) {
        List<String> neighbors = new ArrayList<>();
        if (state.charAt(1) != state.charAt(2))
            neighbors.add(flipDigit(state, 0));
        neighbors.add(flipDigit(state, 1));
        if (state.charAt(0) != state.charAt(1))
            neighbors.add(flipDigit(state, 2));
        return neighbors;
    }

    private static String flipDigit(String state, int index) {
        return state.substring(0, index)
                + (state.charAt(index) == '0' ? '1' : '0')
                + state.substring(index + 1);
    }
}

JDK: List, String
•Graph

[7.7]

a)If we let the lower-case letters a and b stand for the women and A and B for their husbands, we can write each state of the puzzle as a pair of strings such as “a | bAB•”, where the first string is the group on the left bank, the second string the group on the right, and the position of the boat is indicated by ‘•’. Only six other states are reachable from starting state “abAB• |”:

bAB | a•  aAB | b•  aA | bB•  bB | aA•  AB | ab•  ab | AB•

Notice that the two states “bAB | a•” and “aAB | b•” are equivalent since one can be obtained from the other by renaming the two couples; similarly, “aA | bB•” is equivalent to “bB | aA•”. If we continue from here, advancing from newly discovered states and combining equivalent ones if possible, we obtain the graph shown in Fig. C.10. It takes five steps to reach the destination “| abAB•”.

(-tikz- diagram)

Figure C.10. The graph of the jealous couples problem.

b)The JealousCouples.State record in Listing C.51 describes the current state of the puzzle using four values: the position of the boat boatPos and three bit sets that hold the people on the left and right riverbank and the island. We store the bits set in an array of 64-bit integers groups and a normalized version of these sets in normalizedGroups; as we will explain below, these normalized sets allows us to identify puzzle states that are equivalent to states that have already been explored. We omit the implementation of toString(), which prints an instance of State in a format similar to the one discussed in the answer to part (a). To be able to store State objects in hash tables we override equals() and hashCode(); notice that both methods use normalizedGroups instead of groups.

Listing C.51ch7โ€ฏ/โ€ฏJealousCouples

public record State(
        int boatPos,  // location of the boat (0, 1, 2)
        long[] groups,  // bit set of people at each location
        long[] normalizedGroups)  // normalized version of 'groups'
{
    @Override
    public boolean equals(Object obj) {
        return (obj instanceof State state)
                && boatPos == state.boatPos
                && Arrays.equals(normalizedGroups, state.normalizedGroups);
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(boatPos) * 31
                + Arrays.hashCode(normalizedGroups);
    }
}

JDK: Arrays, Integer
•Bits: iterate()

The puzzle itself can now be modeled as a graph with nodes of type State. This graph has two parameters: the number of couples and a Boolean that indicates whether there is an island (Listing C.52).

Listing C.52ch7โ€ฏ/โ€ฏJealousCouples

public class JealousCouples
        implements Graph<JealousCouples.State> {
    int numCouples;
    int numLocations;

    public JealousCouples(int numCouples, boolean hasIsland) {
        this.numCouples = numCouples;
        this.numLocations = hasIsland ? 3 : 2;
    }

    // ...
}

•Graph
: State

We allow up to 26 couples and use integers between 0 and 25 for the wives and integers between 26 and 51 for their husbands. The set representation makes it easy to determine whether a particular group provokes no jealousy: That’s the case if the set of women without their partner present is empty (womenAlone == 0) or if no men are present in the first place (men == 0). Both quantities can be computed using bit operations (Listing C.53).

Listing C.53ch7โ€ฏ/โ€ฏJealousCouples

static final int MAX_COUPLES = 26;
static final long WOMEN_MASK = Bits.range(0, MAX_COUPLES);
static final long MEN_MASK =
        Bits.range(MAX_COUPLES, 2 * MAX_COUPLES);

static boolean noJealousy(long group) {
    long men = group & MEN_MASK;
    long women = group & WOMEN_MASK;
    long womenAlone = women & ~(men >>> MAX_COUPLES);
    return womenAlone == 0 || men == 0;
}

•Bits: range()
•JealousCouples

We can now tackle the problem of computing the neighbors of a given State in the puzzle’s graph. Every legal move involves sending one or two people and the boat from its current location to another location. We can therefore construct all potential new states by iterating over all possible destinations and all possible pairs of passengers and keeping only those states that don’t violate the “no jealousy” rule, as shown in Listing C.54. Notice that the innermost loop starts at j = i, so trips in which only a single person uses the boat are also generated.

Listing C.54ch7โ€ฏ/โ€ฏJealousCouples

@Override
public Collection<State> neighbors(State state) {
    var neighbors = new HashSet<State>();
    var here = state.groups[state.boatPos];
    for (int d = 1; d < numLocations; d++) {
        int dest = (state.boatPos + d) % numLocations;
        for (int i : Bits.iterate(here)) {
            for (int j : Bits.iterate(here & Bits.range(i)))
                checkTrip(state, Bits.bits(i, j), dest, neighbors);
        }
    }
    return neighbors;
}

A trip is allowed only if the new groups at the current location and the destination provoke no jealousy (if this is the case, the group of passengers is guaranteed to provoke no jealousy). The checkTrip() method in Listing C.55 performs the necessary checks and adds a new state to neighbors if successful.

Listing C.55ch7โ€ฏ/โ€ฏJealousCouples

private void checkTrip(State state,
        long passengers, int destination,
        Collection<State> neighbors) {
    long newHere = state.groups[state.boatPos] & ~passengers;
    long newThere = state.groups[destination] | passengers;
    if (noJealousy(newHere) && noJealousy(newThere)) {
        var newGroups = Arrays.copyOf(state.groups, numLocations);
        newGroups[state.boatPos] = newHere;
        newGroups[destination] = newThere;
        neighbors.add(makeState(destination, newGroups));
    }
}

As we noted in the solution of part (a), two puzzle states are equivalent if one can be obtained from the other by renaming the couples. For example, if we already investigated “bB | aA•” there is no need to investigate “aA | bB•” as well because we will only find permutations of previous solutions.

We can identify equivalent states by mapping each state to a unique normalized representative. One way to choose this representative is to reorder the couples in such a way the women appear in alphabetical order when read from left to right. For example, we can normalize “cdC | abAB | D” by performing the substitutions \(\text {c}\to \text {a}\), \(\text {d}\to \text {b}\), \(\text {b}\to \text {c}\), and \(\text {a}\to \text {d}\) (and likewise for the upper-case letters), which gives us the state “abA | cdCD | B” in which the order of the women is “abcd”.

The makeState() method in Listing C.56 performs this normalization by iterating over the women in the three bit sets and assigning each of them (and her husband) a new index based on the order in which she is encountered. The method returns a new State object.

Listing C.56ch7โ€ฏ/โ€ฏJealousCouples

private State makeState(int boat, long[] groups) {
    long[] newGroups = new long[numLocations];
    int newId = 0;
    for (int i = 0; i < numLocations; i++) {
        long women = groups[i] & WOMEN_MASK;
        for (int woman : Bits.iterate(women)) {
            // Assign new ID to woman and her husband
            newGroups[i] |= Bits.bit(newId);
            for (int j = 0; j < groups.length; j++) {
                if (Bits.contains(groups[j], woman + MAX_COUPLES))
                    newGroups[j] |= Bits.bit(newId + MAX_COUPLES);
            }
            newId++;
        }
    }
    return new State(boat, groups, newGroups);
}

Using makeState(), we can also construct the starting state and the end state, in which all couples are at either the first or the second location (Listing C.57).

Listing C.57ch7โ€ฏ/โ€ฏJealousCouples

private long everyone() {
    return Bits.range(0, numCouples)
            | Bits.range(MAX_COUPLES, MAX_COUPLES + numCouples);
}

public State start() {
    return makeState(0, new long[]{everyone(), 0L, 0L});
}

public State end() {
    return makeState(1, new long[]{0L, everyone(), 0L});
}

c)If there is an island, the problem has a solution for all \(n\ge 2\). For \(n=2\) and \(n=3\) the solutions are identical to the problem without an island. For \(n\ge 5\) the number of steps is always \(4n+1\); see the article by Pressman and Singmaster [78] for a mathematical proof.

.
\(n\) 2 3 4 5 6 7 8 9 10
number of trips 5 11 16 21 25 29 33 37 41

[7.8]

a)The two problems are closely related since there is a one-to-one correspondence between states of the problem: If \(L\) and \(S\) denote the amount of water in the large and small jug and \(A\) the amount of water in the additional jug, we always have \(A=8-L+S\). Evenly dividing the original amount of water means we are searching for a path from \(A=8,L=0,S=0\) to \(A=4,L=4,S=0\), that is, from the “00” state to the “40” state in the die-hard graph. As we saw in Fig. 7.1, this requires seven steps.

b)The resulting graph is shown in Fig. C.11; the three numbers in the label of each node indicate the amount of water in the three jugs. We start at the node labeled 006 in which all water is in the third jug. As you can see, the overall shape of the graph is similar to the die-hard graph in Fig. 7.2, but restricting the total amount of water renders three of the original nodes in the upper-right corner inaccessible and causes changes to some of the edges. The quickest way to measure four gallons is \(006\to 501\to 231\to 204\), and the trivial solution to dividing the initial six gallons evenly is \(006\to 033\).

Figure C.11. Graph for measuring water using three jugs.

c)The implementation in Listing C.58 stores the size of the three jugs in the capacity array and the total amount of water used in totalAmount. The list of nodes computed by nodes() consists of all triples \((x,y,z)\) such that \(x\), \(y\), and \(z\) are below the corresponding capacity and the sum \(x+y+z\) is equal to totalAmount. The neighbors() method computes the neighbors of a state by picking two distinct jugs \(i\) and \(j\) and pouring the contents of \(i\) into \(j\), either until \(i\) is empty or \(j\) is full.

Listing C.58ch7โ€ฏ/โ€ฏThreeJugProblem

public class ThreeJugProblem implements Graph<List<Integer>> {
    private final int[] capacity;
    private final int totalAmount;

    @Override
    public Iterable<List<Integer>> nodes() {
        var n = new ArrayList<List<Integer>>();
        for (int x = 0; x < capacity[0]; x++) {
            for (int y = 0; y < capacity[1]; y++) {
                int z = totalAmount - x - y;
                if (z >= 0)
                    n.add(List.of(x, y, z));
            }
        }
        return n;
    }

    @Override
    public Iterable<List<Integer>> neighbors(List<Integer> node) {
        var n = new ArrayList<List<Integer>>();
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                int transfer = Math.min(
                        node.get(i), capacity[j] - node.get(j));
                if (i == j || transfer == 0)
                    continue;
                var neighbor = new ArrayList<>(node);
                neighbor.set(i, neighbor.get(i) - transfer);
                neighbor.set(j, neighbor.get(j) + transfer);
                n.add(neighbor);
            }
        }
        return n;
    }
}

d)The diameter of the graph in Fig. C.11 is \(6\). The two most difficult measuring problems both involve 6 steps, and the corresponding paths are \(006\to 501\to 231\to 204\to 024\to 420\to 402\) and \(303\to 501\to 231\to 204\to 024\to 420\to 402\).

[7.9]

a)The \(\text {Hanoi}(3)\) and \(\text {Hanoi}(4)\) graphs are shown in Fig. C.12. For large values of \(n\), the graph increasingly looks like the Sierpiński triangle we already met in Section 1.1.

(-tikz- diagram)

Figure C.12. The Hanoi(3) and Hanoi(4) graphs

The graph \(\text {Hanoi}(n)\) has \(3^n\) nodes since there are three ways to place largest disk, three ways to place the second-largest disk, and so on. The number of edges \(E_n\) satisfies the following recurrence relation:

\begin{equation} E_0 = 0,\qquad E_n = 3E_{n-1} + 3. \end{equation}

Using induction, it’s easy to prove that \(E_n=(3^{n+1}-3)/2\).

b)Every legal move transfers the topmost disk from one peg to another peg. The labels of neighboring nodes differ in exactly one letter, and the letter that changes in either label is always the rightmost instance of A, B, or C. We can state this mathematically as follows: There is an edge between two nodes \(X\) and \(Y\) if their labels differ in exactly one position \(i\), and if the letter \(X_i\) is the rightmost A, B, or C in \(X\) and the letter \(Y_i\) is the rightmost A, B, or C in \(Y\).

The HanoiGraph class in Listing C.59 uses these conditions to compute the Hanoi graph. The neighbors() method first precomputes an array topDisk that holds the smallest disk on each of the three pegs; the number \(0\) represents the largest disk and \(n-1\) the smallest. If one of the pegs is empty, the corresponding entry in topDisk is set to \(-1\). For example, for the AABAB state, topDisk is {3, 4, -1} since disk 3 is the topmost disk on peg A, disk 4 the topmost disk on peg B, and peg C is empty. Moving a disk from peg to targetPeg is only allowed if topDisk[peg] isn’t \(-1\) and

topDisk[targetPeg] < topDisk[peg]

Notice that this condition also handles the case where the target peg is empty, since in this case topDisk[targetPeg] contains the value \(-1\).

Listing C.59ch7โ€ฏ/โ€ฏHanoiGraph

public record HanoiGraph(int numDisks) implements Graph<String> {
    @Override
    public List<String> neighbors(String state) {
        int[] topDisk = new int[3];
        for (int peg = 0; peg < 3; peg++)
            topDisk[peg] = state.lastIndexOf('A' + peg);
        var neighbors = new ArrayList<String>();
        for (int disk : topDisk) {
            if (disk == -1)
                continue;  // no disk on current peg
            for (int targetPeg = 0; targetPeg < 3; targetPeg++) {
                if (topDisk[targetPeg] < disk) {
                    neighbors.add(state.substring(0, disk)
                            + (char) ('A' + targetPeg)
                            + state.substring(disk + 1));
                }
            }
        }
        return neighbors;
    }
    // ...
}

c)To find the shortest path between two corners of the Hanoi graph, breadth-first search has to visit almost every node of the graph. In contrast, the recursive algorithm in Exercise 3.8 computes the shortest path directly, without wasting time on nodes that don’t lie on the path. Since \(\text {Hanoi}(n)\) has \(3^n\) nodes but its side length is “just” \(2^n\), breadth-first search has to evaluate \((3/2)^n\) times more nodes than the dedicated algorithm — it literally has to work exponentially harder!

d)For \(\text {Hanoi}(2)\), a possible Hamiltonian cycle is

\begin{equation*} \text {AA}\to {}\text {AC}\to {}\text {BC}\to {}\text {BB}\to {}\text {BA}\to {}\text {CA}\to {}\text {CC}\to {}\text {CB}\to {}\text {AB}\to {}\text {AA}. \end{equation*}

Likewise, for \(\text {Hanoi}(3)\) a possible Hamiltonian cycle is

\begin{gather*} \text {ACC}\to {}\text {ACA}\to {}\text {ACB}\to {}\text {AAB}\to {}\text {AAA}\to {}\text {AAC}\to {}\text {ABC}\to {}\text {ABA}\to {}\text {ABB}\to {}\\ \text {CBB}\to {}\text {CBA}\to {}\text {CBC}\to {}\text {CAC}\to {}\text {CAA}\to {}\text {CAB}\to {}\text {CCB}\to {}\text {CCA}\to {}\text {CCC}\to {}\\ \text {BBB}\to {}\text {BBA}\to {}\text {BBC}\to {}\text {BAC}\to {}\text {BAA}\to {}\text {BAB}\to {}\text {BCB}\to {}\text {BCA}\to {}\text {BCC}\to {}\text {ACC}. \end{gather*} Other solutions can be found by reversing these paths or shifting them circularly.

e)First note that every Hanoi graph consists of three smaller Hanoi graphs that are connected at the edges, as shown in Fig. C.13. Let’s say we want to construct a Hamiltonian path \(P_n(A_0, C_0)\) that connects the corners \(A_0\) and \(C_0\) of \(\text {Hanoi}(n)\). We show that this is possible for every value of \(n\). For \(\text {Hanoi}(1)\), the Hamiltonian path simply connects the three corners \(A_0\to {}B_0\to {}C_0\). For \(n>1\), we recursively construct suitable Hamiltonian paths for the three sub-graphs and connect them at the edges:

\begin{equation*} P_n(A_0, C_0) = P_{n-1}(A_0, A_1) \to {} P_{n-1}(B_2, B_1) \to {} P_{n-1}(C_2, C_0). \end{equation*}

It follows by induction that every Hanoi graph contains a Hamiltonian path between any pair of corners.

Figure C.13. The recursive structure of Hanoi graphs. Every Hanoi graph consists of three smaller Hanoi graphs that are joined at their corners. The edge connecting the graphs corresponds to moving the largest disk to a different peg.

We can use a similar construction to show that every Hanoi graph also contains a Hamiltonian cycle. Assume we want to construct a Hamiltonian cycle in \(\text {Hanoi}(n)\) that starts and ends at the \(A_2\) node in Fig. C.13. Since the cycle must visit every node exactly once, it must have the following general form:

\begin{equation*} C_n = P_{n-1}(A_2, A_1) \to {} P_{n-1}(B_2, B_1) \to {} P_{n-1}(C_2, C_1) \to {} A_2, \end{equation*}

where each \(P_{n-1}\) is a Hamiltonian path through one of the smaller Hanoi graphs. We just saw that it is always possible to construct the paths \(P_{n-1}\), so there is a Hamiltonian cycle \(C_n\) for every value of \(n\).

[7.10]

a)If the starting pixel already has the desired color, the algorithm does nothing and returns immediately. Listing C.60 shows an implementation for images of type BufferedImage:

Listing C.60ch7โ€ฏ/โ€ฏFloodFill

record PixelPos(int x, int y) {}

// Fill the region connected to the pixel (startX, startY)
// with a new color. Process one pixel at a time.
public static void floodFill_pixelBased(BufferedImage image,
        int startX, int startY, int fillColor) {
    int startColor = image.getRGB(startX, startY);
    if (image.getRGB(startX, startY) == fillColor)
        return;
    var queue = new ArrayDeque<PixelPos>();
    queue.add(new PixelPos(startX, startY));
    while (!queue.isEmpty()) {
        PixelPos pixelPos = queue.poll();
        int x = pixelPos.x(), y = pixelPos.y();
        image.setRGB(x, y, fillColor);
        if (x > 0 && image.getRGB(x - 1, y) == startColor) {
            queue.add(new PixelPos(x - 1, y));
        }
        if (x < image.getWidth() - 1
                && image.getRGB(x + 1, y) == startColor) {
            queue.add(new PixelPos(x + 1, y));
        }
        if (y > 0 && image.getRGB(x, y - 1) == startColor) {
            queue.add(new PixelPos(x, y - 1));
        }
        if (y < image.getHeight() - 1
                && image.getRGB(x, y + 1) == startColor) {
            queue.add(new PixelPos(x, y + 1));
        }
    }
}

b)There is a total of eleven spans:

(-tikz- diagram)

The following spans are adjacent: \(0\Edge {}4\Edge {}8\), \(1\Edge {}5\), \(2\Edge {}6\Edge {}10\), \(3\Edge {}7\).

c)Let’s start with a more detailed description of the span-based flood fill algorithm:

  • • We use a queue to keep track of unprocessed spans. It isn’t necessary to determine the extent of each span in advance. Instead, each entry in the queue can be a single pixel somewhere on the span to be filled.

  • • When processing each span, we first determine its left edge by moving to the left. We then move to the right and replace all pixels on the span with the desired fill color.

  • • While moving right, we inspect the pixels above and below the current pixel and check if they also have the starting color. If they do, they are part of another span that needs to be filled and we add their coordinates to the queue. Only the first pixel of each span above or below should be added to the queue so that each span is processed only once.

Listing C.61 shows an implementation of this idea.

Listing C.61ch7โ€ฏ/โ€ฏFloodFill

// Fill the region connected to the pixel (startX, startY)
// with a new color. Process horizontal spans of pixels.
public static void floodFill_spanBased(
        BufferedImage image, int startX, int startY, int fillColor) {
    int startColor = image.getRGB(startX, startY);
    if (image.getRGB(startX, startY) == fillColor)
        return;
    var queue = new ArrayDeque<PixelPos>();
    queue.add(new PixelPos(startX, startY));
    while (!queue.isEmpty()) {
        PixelPos pixelPos = queue.poll();

        // Move to the start of the current span.
        int x = pixelPos.x();
        int y = pixelPos.y();
        while (x > 0 && image.getRGB(x - 1, y) == startColor)
            x--;

        // Color pixels on this span and find new spans above and below.
        boolean skipSpanAbove = false;
        boolean skipSpanBelow = false;
        while (x < image.getWidth()
                && image.getRGB(x, y) == startColor) {
            image.setRGB(x, y, fillColor);
            boolean matchingColorAbove = y > 0
                    && image.getRGB(x, y - 1) == startColor;
            boolean matchingColorBelow = y < image.getHeight() - 1
                    && image.getRGB(x, y + 1) == startColor;
            if (matchingColorAbove && !skipSpanAbove)
                queue.add(new PixelPos(x, y - 1));
            if (matchingColorBelow && !skipSpanBelow)
                queue.add(new PixelPos(x, y + 1));
            skipSpanAbove = matchingColorAbove;
            skipSpanBelow = matchingColorBelow;
            x++;
        }
    }
}

JDK: ArrayDeque, BufferedImage
•FloodFill: PixelPos

Chapter 8

[8.1]

For simplicity, we assume that levels are stored as arrays of Strings, for example as follows:

public static String[] sokoban1 = {
        "    #####",
        "    #   #",
        "    #$  #",
        "  ###  $##",
        "  #  $ $ #",
        "### # ## #   ######",
        "#   # ## #####  ..#",
        "# $  $          ..#",
        "##### ### #@##  ..#",
        "    #     #########",
        "    #######"
};

The parse() method in Listing C.62 constructs an instance of Level from such an array of strings. The function first determines the level’s width and height by counting the number of columns and rows in the textual description and then iterates over the rows a second time to place the individual objects.

Listing C.62ch8โ€ฏ/โ€ฏLevel

public static Level parse(String[] rows) {
    int width = 0;
    for (String row : rows)
        width = Math.max(width, row.length());
    int height = rows.length;
    var level = new Level(width, height);
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < rows[y].length(); x++) {
            level.setCode(x, y, rows[y].charAt(x));
        }
    }
    return level;
}

[8.2]

Like the other methods defined in GameState, the toString() method shown in Listing C.63 takes an additional argument of type Level. It iterates over the rows and columns of the level and computes the correct character code for each square.

Listing C.63ch8โ€ฏ/โ€ฏGameState

// Return the ASCII representation of this game state.
public String toString(Level level) {
    var sb = new StringBuilder();
    for (int y = 0; y < level.height(); y++) {
        for (int x = 0; x < level.width(); x++) {
            char charCode;
            int index = level.index(x, y);
            if (level.walls().contains(index)) {
                charCode = '#';
            } else if (index == workerPos) {
                charCode =
                        level.goals().contains(index) ? '+' : '@';
            } else if (crates.contains(index)) {
                charCode =
                        level.goals().contains(index) ? '*' : '$';
            } else {
                charCode =
                        level.goals().contains(index) ? '.' : ' ';
            }
            sb.append(charCode);
        }
        sb.append('\n');
    }
    return sb.toString();
}

[8.3]

A level is closed if no positions on the boundary of the level can be reached from the worker’s starting position. The solution in Listing C.64 first constructs the move graph of the level with all crates removed and then uses breadth-first search to check whether it is possible to reach any position on the boundary.

Listing C.64ch8โ€ฏ/โ€ฏLevelClosed

public static boolean isLevelClosed(Level level) {
    var moveGraph = new MoveGraph(level, new BitSet());
    Integer posOutside = moveGraph.scan(
            level.workerStart(),
            pos -> level.getX(pos) == 0 || level.getY(pos) == 0
                    || level.getX(pos) == level.width() - 1
                    || level.getY(pos) == level.height() - 1);
    return posOutside == null;
}

[8.4]

We first compute the interior of the level using breadth-first search. For each interior position that is not occupied by a crate and not already in a known component, we then use breadth-first search again to find all the nodes it is connected to, which gives us the next component. For an implementation, see Listing C.65.

Listing C.65ch8โ€ฏ/โ€ฏComponents

static List<BitSet> findComponents(Level level, BitSet crates) {
    var interior = new BitSet();
    new MoveGraph(level, new BitSet())
            .visitNodes(level.workerStart(), interior::add);
    var inComponent = new BitSet();
    var components = new ArrayList<BitSet>();
    for (int pos : interior) {
        if (!crates.contains(pos) && !inComponent.contains(pos)) {
            var component = new BitSet();
            new MoveGraph(level, crates)
                    .visitNodes(pos, component::add);
            components.add(component);
            inComponent.addAll(component);
        }
    }
    return components;
}

[8.5]

A function compressMoves() that compresses a string of movement commands is shown in Listing C.66. The compressed solution of Level 1 is:

u3l3uLUllDDuuruurDldldll3dr12RurD
14lulld15R
13l3urrdD3uruul4Dull3dr11RurD
13l3urrdDuull3dr11R
7l3ulLul3D4urrDlldll3dr10RdrUluRR
lld6l3uLLul3Duull3dr10RdrUluR

Listing C.66ch8โ€ฏ/โ€ฏSokobanSolver

// Replace runs of identical letters with an integer followed
// by a single letter
static String compressMoves(String moves) {
    var sb = new StringBuilder();
    for (int i = 0; i < moves.length(); i++) {
        char move = moves.charAt(i);
        int count = 1;
        while (i < moves.length() - 1
                && moves.charAt(i + 1) == move) {
            i++;
            count++;
        }
        if (count > 2)
            sb.append(count);
        else if (count == 2)
            sb.append(move);
        sb.append(move);
    }
    return sb.toString();
}

[8.6]

Changing the order of neighbors doesn’t affect the length of the shortest path through the push graph, but it does cause breadth-first search to discover a different solution first. With the standard order, the solver favors nearby crates, which leads to a solution in which the total distance traveled by the worker is fairly small (but not minimal, as we will discuss in Section 8.5). Reversing the list of neighbors, on the other hand, favors far-away crates, which produces a solution in which the worker constantly alternates between different crates. In the case of Level 1, the resulting solution requires 926 steps and starts as follows:

u3l3uLUluurDldlDll3drRll3urrDull3drr4R6l3urrdDuull3drRdd4ruu

This solution also requires the minimum 97 pushes.

[8.7]

Node E has a total of eight neighbors that correspond to moving the left or the right crate in each of four directions. Moving the left crate up brings us back to the starting node S. The remaining options are moving the left crate down (E1), right (E2), left (E3), and moving the right crate up (E4), down (E5), left (E6), or right (E7).

[8.8]

a)Figure C.14 marks all dead squares in the level using an X.

Figure C.14. Dead positions in a Sokban level. The positions marked with an X are dead: it is impossible to push a crate from any of those positions to one of the two goal squares.

b)One way to show that a position \(p\) is dead is to place a single crate at \(p\) and show that, regardless of the worker’s position, the resulting level cannot be solved. (The only positions of the worker that must be checked are the four squares next to \(p\).) If we repeat this for all positions \(p\) inside the level, we obtain the list of all dead squares.

We can solve the problem more efficiently by considering the reverse problem: Which positions in a level are reachable by pulling a crate that starts at one of the goal squares? Similar to the push graph, we can define a pull graph in which two positions are adjacent if the worker can pull a crate from one position to the other. To compute the list of dead squares, we first determine all reachable positions in the level and then successively remove positions that are reachable by repeatedly pulling a crate from each of the goals. The positions that remain are the level’s dead squares. An implementation is shown in Listing C.67.

Listing C.67ch8โ€ฏ/โ€ฏDeadSquares

public static BitSet computeDeadSquares(Level level) {
    // An edge x -> y in the following graph indicates that a
    // crate can be pulled from position x to position y.
    var pullGraph = new Graph<Integer>() {
        public List<Integer> neighbors(Integer pos) {
            var neighbors = new ArrayList<Integer>();
            for (var direction : Board.ALL_DIRECTIONS) {
                int neighbor = level.moveIndex(pos, direction);
                if (neighbor == -1)
                    continue;
                int worker = level.moveIndex(neighbor, direction);
                if (worker == -1)
                    continue;
                if (!level.walls().contains(neighbor) &&
                        !level.walls().contains(worker)) {
                    neighbors.add(neighbor);
                }
            }
            return neighbors;
        }
    };
    // Start with the interior of the level, then remove squares that
    // can be reached by pulling a crate from any of the goal squares.
    var deadSquares = new BitSet();
    new MoveGraph(level, new BitSet())
            .visitNodes(level.workerStart(), deadSquares::add);
    for (int goal : level.goals())
        pullGraph.visitNodes(goal, deadSquares::remove);
    return deadSquares;
}

[8.9]

a)The UKACD is stored as a text file that contains one entry per line. The readWords() method in Listing C.68 reads the entire file and creates a list of entries that contain only alphabetic characters and have the correct length wordLength. As a special case, the functions returns all words if the wordLength parameter is negative.

Listing C.68ch8โ€ฏ/โ€ฏwordsโ€ฏ/โ€ฏWordList

// Read all words of the given length from the file at 'path'.
// Each line is assumed to contain a single word.
public static Collection<String> readWords(
        String path, int wordLength) throws IOException {
    var words = new ArrayList<String>();
    var reader = new BufferedReader(new FileReader(path));
    while (reader.ready()) {
        String entry = reader.readLine().toLowerCase();
        if (entry.matches("[a-zA-Z]*") &&
                (entry.length() == wordLength || wordLength < 0)) {
            words.add(entry);
        }
    }
    return words;
}

b)The neighbors of HAPPY are contained in four buckets: APPY, HPPY, HAPY, and HAPP. (The bucket HAPY corresponds to deleting either occurrence of the letter P.) HARPY belongs to five buckets: ARPY, HRPY, HAPY, HARY, and HARP.

c)A word \(w\) of length \(n\) must be added to \(n\) buckets, and the key of the \(k\)th bucket is obtained by deleting the \(k\)th letter of \(w\); see Listing C.69. Likewise, to find the neighbors of a word \(w\), we inspect all matching buckets and pick those entries that differ from \(w\) in exactly one letter.

Listing C.69ch8โ€ฏ/โ€ฏwordsโ€ฏ/โ€ฏSimilarWords

private void addWord(String word) {
    for (int i = 0; i < word.length(); i++) {
        String key = deleteLetter(word, i);
        buckets.computeIfAbsent(key, k -> new HashSet<>()).add(word);
    }
}

public Collection<String> findSimilarWords(String word) {
    var result = new ArrayList<String>();
    for (int i = 0; i < word.length(); i++) {
        for (String n : buckets.get(deleteLetter(word, i))) {
            int distance = 0;  // number of letters that differ
            for (int j = 0; j < n.length() && distance <= 1; j++) {
                if (n.charAt(j) != word.charAt(j))
                    distance++;
            }
            if (distance == 1)
                result.add(n);
        }
    }
    return result;
}

private static String deleteLetter(String word, int index) {
    var sb = new StringBuilder(word);
    sb.deleteCharAt(index);
    return sb.toString();
}

d)The WordLadderGraph class shown in Listing C.70 computes the word ladder graph for an arbitrary set of words. The nodes of this graph are stored in the words field, and its edges are computed on the fly.

Listing C.70ch8โ€ฏ/โ€ฏwordsโ€ฏ/โ€ฏWordLadderGraph

public class WordLadderGraph implements Graph<String> {
    private final Set<String> words;
    private final SimilarWords similar;

    public WordLadderGraph(Collection<String> words) {
        this.words = new HashSet<>(words);
        similar = new SimilarWords(words);
    }

    @Override
    public Collection<String> nodes() {return words;}

    @Override
    public Collection<String> neighbors(String word) {
        if (!words.contains(word))
            return Collections.emptyList();
        return similar.findSimilarWords(word);
    }
}

e)Four steps are necessary to transform ROCK into GOLD:

\[ \text {ROCK}\to {}\text {ROOK}\to {}\text {GOOK}\to {}\text {GOOD}\to {}\text {GOLD}. \]

To compute the list of words that cannot be transformed into GOLD, traverse the graph starting at GOLD and afterward report all nodes that weren’t reached; there are 90 such words. The words ETNA and ODIN have the largest distance 11 from GOLD.

f)The longest word ladder is the one between ISLA and ZEBU:

\begin{gather*} \text {ISLA}\to {}\text {ISLE}\to {}\text {IDLE}\to {}\text {IDLY}\to {}\text {ILLY}\to {}\text {ALLY}\to {}\text {ALAY}\to {}\text {FLAY}\to {}\text {FLEY}\to {}\\ \text {GLEY}\to {}\text {GOEY}\to {}\text {GOBY}\to {}\text {GOBO}\to {}\text {ZOBO}\to {}\text {ZOBU}\to {}\text {ZEBU} \end{gather*} There are four pairs of words that can be transformed into their reverse: REVILER/RELIVER, REVILED/DELIVER, DEIFIER/REIFIED, STENNED/DENNETS.

[8.10]

a)The distribution of light is shown in Fig. C.15.

Figure C.15. Final distribution of light

b)Every object either emits light by itself or reflects incoming light. To model this behavior, we use the interface LaserPiece defined in Listing C.71, which defines two methods: emit() returns the directions in which incoming light is emitted and reflect() the directions in which light is reflected. We use the Direction class defined in Listing 8.3 to represent the four directions up, down, left, and right. The listing also defines two simple pieces: the empty square (EMPTY), which transmits incoming light unchanged, and the solid block (BLOCKER), which absorbs all incoming light. EMPTY is implemented as a function that returns a list that contains just the direction of the incoming light ray, and BLOCKER as a function that returns an empty list regardless of the incoming light.

Listing C.71ch8โ€ฏ/โ€ฏlasersโ€ฏ/โ€ฏLaserPiece

public interface LaserPiece {
    default List<Board.Direction> emit() {
        return List.of();
    }

    List<Board.Direction> reflect(Board.Direction incoming);

    LaserPiece EMPTY = List::of;
    LaserPiece BLOCKER = incoming -> List.of();
}

JDK: List
•Board: Direction

A laser is another simple LaserPiece: it emits light in a single fixed direction but doesn’t reflect any incoming light (Listing C.72).

Listing C.72ch8โ€ฏ/โ€ฏlasersโ€ฏ/โ€ฏEmitter

record Emitter(Board.Direction direction) implements LaserPiece {
    @Override
    public List<Board.Direction> reflect(Board.Direction incoming) {
        return List.of();
    }

    @Override
    public List<Board.Direction> emit() {
        return List.of(direction);
    }
}

A more complex object is the transparent mirror because the direction of the outgoing rays depends both on the direction of the incoming ray and the orientation of the mirror. To implement reflect(), we create a table that maps all possible combinations of mirror orientations and incoming rays to the resulting outgoing directions (Listing C.73). For instance, the first key “|l” represents a vertical mirror and an incoming ray that moves towards the left, and the associated value is a list of two directions that indicates that the ray splits into two and continues to the left and to the right. The other orientations of the mirror are encoded as “\”, “-”, and “/”. The reflect() method returns the list of directions in which an incoming light ray is split; this is either one of the values stored in map or the empty list when the light ray is blocked.

Listing C.73ch8โ€ฏ/โ€ฏlasersโ€ฏ/โ€ฏTransparentMirror

record TransparentMirror(String orientation) implements LaserPiece {
    static Map<String, List<Board.Direction>> map = Map.ofEntries(
            Map.entry("|l", List.of(LEFT, RIGHT)),
            Map.entry("|r", List.of(LEFT, RIGHT)),
            Map.entry("-u", List.of(UP, DOWN)),
            Map.entry("-d", List.of(UP, DOWN)),
            Map.entry("/r", List.of(UP, RIGHT)),
            Map.entry("/u", List.of(UP, RIGHT)),
            Map.entry("/l", List.of(LEFT, DOWN)),
            Map.entry("/d", List.of(LEFT, DOWN)),
            Map.entry("\\u", List.of(UP, LEFT)),
            Map.entry("\\l", List.of(UP, LEFT)),
            Map.entry("\\r", List.of(RIGHT, DOWN)),
            Map.entry("\\d", List.of(RIGHT, DOWN)));

    @Override
    public List<Board.Direction> reflect(Board.Direction incoming) {
        return map.getOrDefault(orientation + incoming.charCode(),
                List.of());
    }
}

c)The key idea is to model the problem as a graph in which each square on the board is represented by four nodes, one for each of its four sides. We can label the nodes using tuples of the form \((p,d)\), where \(p\) is the position of the square and \(d\) a direction (up, down, left, or right). The node \((p,d)\) represents a ray of light that leaves the square \(p\) in direction \(d\).

An implementation of this idea is shown in Listing C.74. The LaserBoard class extends the Board class we developed for representing Sokoban levels, which simplifies the task of computing with positions on the board and directions. It also implements the Graph interface: Each node represents a ray of light that starts at a certain position moves in a certain direction.

Listing C.74ch8โ€ฏ/โ€ฏlasersโ€ฏ/โ€ฏLaserBoard

// A graph for simulating the propagation of light on a
// rectangular board.
public class LaserBoard extends Board
        implements Graph<LaserBoard.Ray> {
    public record Pos(int x, int y) {
    }

    public record Ray(Pos pos, Direction direction) {
    }

    private Map<Pos, LaserPiece> pieces = new HashMap<>();

    public LaserBoard(int width, int height) {
        super(width, height);
    }

    public void setPiece(int x, int y, LaserPiece piece) {
        pieces.put(new Pos(x, y), piece);
    }

    // ...
}

To compute the neighbors of a node ray in this graph, we first look up the object the ray hits next and then reflect it depending on the object’s type and the ray’s current direction (Listing C.75).

Listing C.75ch8โ€ฏ/โ€ฏlasersโ€ฏ/โ€ฏLaserBoard

// Each ray is connected to the rays it spawns in
// neighboring squares.
@Override
public List<Ray> neighbors(Ray ray) {
    Pos neighbor = new Pos(ray.pos.x + ray.direction.xOff(),
            ray.pos.y + ray.direction.yOff());
    if (!isInside(neighbor.x(), neighbor.y()))
        return List.of();
    var newRays = new ArrayList<Ray>();
    LaserPiece piece =
            pieces.getOrDefault(neighbor, LaserPiece.EMPTY);
    for (var direction : piece.reflect(ray.direction))
        newRays.add(new Ray(neighbor, direction));
    return newRays;
}

We can now simulate the propagation of light as shown in Listing C.76. For every LaserPiece on the board, we first call emit() to determine the outgoing rays of light, and then follow each such ray by traversing the graph using breadth-first search. Every Ray discovered by visitNodes() is stored in a set rays that represents the final distribution of light on the board. For example, the resulting set of rays for the board in Fig. 8.10 can be visualized as follows:

.... .d.. .... .... .d.. .... 
.... udl. ..l. ..l. udlr ...r 
.... ud.. .... .... ud.. .... 
..l. udlr ..lr ..lr u.l. .... 

Listing C.76ch8โ€ฏ/โ€ฏlasersโ€ฏ/โ€ฏLaserBoard

// Simulate the propagation of light by following the rays
// emitted by each piece on the board.
public Set<Ray> simulateLight() {
    var rays = new HashSet<Ray>();
    for (Pos p : pieces.keySet()) {
        var piece = pieces.get(p);
        for (var direction : piece.emit()) {
            var ray = new Ray(p, direction);
            visitNodes(ray, rays::add);
        }
    }
    return rays;
}

[8.11]

a)We can model the board as a weighted graph in which each node corresponds to a position on the board. Using the Board and WeightedGraph types developed in this chapter, we define a graph CivBoard that models the movement on the board (Listing C.77). The terrain field holds the type of terrain for every square on the board: We use “␣” for grasslands, “f” for forests, “w” for water, and “m” for mountains.

Listing C.77ch8โ€ฏ/โ€ฏciv

public class CivBoard extends Board
        implements WeightedGraph<CivBoard.Pos> {
    public record Pos(int x, int y) {
    }

    private final List<Character> terrain;

    public CivBoard(int width, int height) {
        super(width, height);
        terrain = new ArrayList<>(
                Collections.nCopies(width * height, ' '));
    }

    char getTerrain(Pos p) {
        return terrain.get(index(p.x(), p.y()));
    }

    // ...
}

For a given position on the board, the outgoing edges point to neighboring positions that are reachable, and the weight of each edge reflects the cost of moving to that position (Listing C.78).

Listing C.78ch8โ€ฏ/โ€ฏcivโ€ฏ/โ€ฏCivBoard

public List<Edge<Pos>> edges(Pos pos) {
    var edges = new ArrayList<Edge<Pos>>();
    for (var dir : ALL_DIRECTIONS) {
        Pos neighbor = new Pos(pos.x + dir.xOff(),
                pos.y + dir.yOff());
        if (!isInside(neighbor.x(), neighbor.y()))
            continue;
        int weight = switch (getTerrain(neighbor)) {
            case ' ' -> 1;
            case 'f' -> 2;
            case 'w' -> getTerrain(pos) == 'w' ? 1 : 3;
            case 'm' -> Integer.MAX_VALUE;
            default -> throw new RuntimeException(
                    "Invalid terrain");
        };
        if (weight != Integer.MAX_VALUE)
            edges.add(new Edge<>(neighbor, weight));
    }
    return edges;
}

b)Figure C.16 shows the distance of every square from G2.

.
A B C D E F G H I J K L M N O P
0 11 9 7 5 4 3 4 5 7 9 11 10 11 12 13 14
1 10 8 6 4 3 2 1 4 6 8 9 9 10 11 12 14
2 10 9 7 5 3 1 0 3 4 6 7 8 9 11 13 15
3 10 9 8 6 4 2 3 4 5 6 7 – 11 12 13 14
4 11 10 – 6 4 3 4 5 6 7 9 – – 13 14 15
5 – – 10 7 5 4 5 7 – 8 9 – – 14 15 16
6 13 12 11 9 8 6 7 9 11 – 10 11 12 13 15 16
7 13 12 11 10 10 8 9 11 13 14 12 12 13 15 18 17
8 14 13 12 11 11 10 11 13 15 16 14 13 14 15 17 18
9 15 14 13 13 13 12 13 15 16 17 15 14 15 17 18 20
10 16 15 15 15 15 13 14 15 16 17 16 15 16 17 19 21
Figure C.16. The distance from G2 to every square on the board.

There several similar shortest paths of length 13 from G2 to M7. One is

\[ \text {G2}\to {}\text {H2}\to {}\text {H3}\to {}\text {H4}\to {}\text {I4}\to {}\text {J4}\to {}\text {J5}\to {}\text {K5}\to {}\text {K6}\to {}\text {L6}\to {}\text {L7}\to {}\text {M7}. \]

Chapter 9

[9.1]

a)Digits and letters occupy consecutive locations in the ASCII code, so two comparisons are enough to implement each of the three functions (Listing C.79).

Listing C.79ch9โ€ฏ/โ€ฏAscii

public static boolean isDigit(char c) {
    return c >= 0x30 && c <= 0x39;
}
public static boolean isLower(char c) {
    return c >= 0x61 && c <= 0x7a;
}
public static boolean isUpper(char c) {
    return c >= 0x41 && c <= 0x5a;
}

b)To convert upper-case letters to lower-case, simply add the offset \(32\) (or 0x20); see Listing C.80.

Listing C.80ch9โ€ฏ/โ€ฏAscii

public static char toLower(char c) {
    return isUpper(c) ? (char) (c + 0x20) : c;
}
public static char toUpper(char c) {
    return isLower(c) ? (char) (c - 0x20) : c;
}

[9.2]

a)The encryptCaesar() function in Listing C.81 first converts upper- and lower-case letters to a number between 0 and 26, then cyclically shifts this number using the modulo operator, and finally converts the number back to an ASCII letter. By using a negative offset, the same method can also be used to decrypt letters.

Listing C.81ch9โ€ฏ/โ€ฏAscii

// Implementation of the Caesar cipher for ASCII characters.
public static int encryptCaesar(char c, int offset) {
    if (isLower(c))
        return Math.floorMod(c - 0x61 + offset, 26) + 0x61;
    if (isUpper(c))
        return Math.floorMod(c - 0x41 + offset, 26) + 0x41;
    return c;
}

b)Because it can be cracked by simply trying all possible offsets. Here we used an offset of 13 which yields a cipher known as ROT13. This cipher is still widely used in Internet forums to obfuscate hints and spoilers. Since ROT13 shifts the Latin alphabet by half its length, encrypting and decrypting are the same operation.

[9.3]

The following code represents “ABRACADABRA” using 13 bits:

.
symbol A BR CA DA
codeword 0 10 110 111

[9.4]

The possible interpretations are, in alphabetical order: ABCCAAABBC, ABCCAAABBRA, ABCCADABC, ABCCADABRA, ABCRAAAABBC, ABCRAAAABBRA, ABCRAADABC, ABCRAADABRA, ABRACAAABBC, ABRACAAABBRA, ABRACADABC, ABRACADABRA, ABRARAAAABBC, ABRARAAAABBRA, ABRARAADABC, ABRARAADABRA.

[9.5]

The tree does not describe a prefix code since the codeword of A is a prefix of the codeword of R. As a result, the node for A appears as an inner node in the corresponding binary tree:

[9.6]

Only the first code is a prefix code, whereas the second one is almost the opposite: Every codeword is a prefix of the one following it in the list. Nevertheless, both codes are unambiguous since every bit sequence produced by either code corresponds to a unique sequence of codewords.

[9.7]

The createFromTable() method in Listing C.82 iterates over the table of codewords and inserts them one by one into a binary tree that is initially empty. Inserting into the tree is accomplished by insert(), which adds the codeword cw to an existing tree rooted at node. Since the Node type is defined as a record and is therefore immutable, every insertion produces a new tree, which is returned by the function. The depth parameter tracks the current depth in the tree. If the depth equals the length of the codeword, a new leaf node is constructed. Otherwise, insert() calls itself recursively to add the codeword into the left or right sub-tree of node, depending on whether the bit at position depth is 0 or 1.

Listing C.82ch9โ€ฏ/โ€ฏPrefixCodeFromTable

private static final Node EMPTY = PrefixCode.makeInner(null, null);

// Construct a binary tree from a table of codewords.
public static Node createFromTable(Codeword[] codewords) {
    Node root = EMPTY;
    for (int symbol = 0; symbol < codewords.length; symbol++)
        root = insert(root, codewords[symbol], symbol, 0);
    return root;
}

// Insert a new codeword into an existing binary tree and return
// a new tree as the result.
private static Node insert(Node node, Codeword cw,
        int symbol, int depth) {
    if (depth == cw.length())
        return PrefixCode.makeLeaf(symbol);
    if (node == null)
        node = EMPTY;
    if (node.symbol() != -1)  // cannot insert into a leaf node
        throw new RuntimeException("Not a prefix code");
    if ((cw.bits() & (1L << (cw.length() - depth - 1))) == 0) {
        Node left = insert(node.left(), cw, symbol, depth + 1);
        return PrefixCode.makeInner(left, node.right());
    } else {
        Node right = insert(node.right(), cw, symbol, depth + 1);
        return PrefixCode.makeInner(node.left(), right);
    }
}

If we encounter a leaf node along the way, the table of codewords does not represent a prefix code. When inserting into a non-existent sub-tree, the line

if (node == null) 
    node = EMPTY;

supplies an empty tree to insert into. This saves a few null checks in the lines that follow.

[9.8]

The optimal prefix code for a single symbol consists of a single codeword of length 1. The corresponding Huffman tree has two nodes: a root node and one leaf. HuffmanTree can be modified by adding the following two lines before line 5:

(image)

[9.9]

The catch is that decoding the 1-bit encoding of ABRACADABRA isn’t possible without knowing the codebook. We have merely shifted the problem of compressing a sequence of bytes to the problem of compressing the codebook.

[9.10]

In the second step of Huffman’s algorithm, there are three ways to choose two nodes with frequency \(2\), which gives us the three prefix trees shown in Fig. C.17; additional equivalent trees can be obtained by exchanging the left and right sub-trees of each of the inner nodes. In total, there are \(3\times 16=48\) possible Huffman tree, all of which are equally good and encode ABRACADABRA using 23 bits.





Figure C.17. Different Huffman trees for the same frequency table

[9.11]

The worst case for Huffman’s algorithm occurs when, after combining two nodes, the new node is placed at the end of the priority queue, that is, if the cumulative frequency of the new node is less than or equal to the frequency of the next unprocessed symbol. In this case, the Huffman tree degenerates into a long chain:

The nodes in this illustration show the smallest frequencies that produce a Huffman tree of height 64: The most frequent symbol would have to occur \(2^{63}\) times, which is never going to happen in practice.

[9.12]

For ABRACADABRA, the Shannon-Fano algorithm constructs either one of the following two prefix codes:

  

There are two possibilities since the second split is either “B | R C D” or “B R | C D”. Both splits are equally good (or, rather, bad): one half contains two and the other four characters. There is an optimal split “B C | R D”, but the Shannon-Fano algorithm doesn’t find it. In this example, it doesn’t matter: Both codes encode ABRACADABRA using 23 bits, just like the Huffman code.

[9.13]

a)The sequence of calls should return the following values:

in.readBits(2);  // returns 0b10
in.readBits(8);  // returns 0b01100100
in.readBits(6);  // returns 0b000001

b)The outline of BitOutputStream is shown in Listing C.83. The class has three fields: out for the underlying byte stream, buffer for buffering unwritten bits, and bufferSize for the number of bits in buffer.

Listing C.83ch9โ€ฏ/โ€ฏBitOutputStream

public class BitOutputStream {
    private final OutputStream out;  // byte stream for output
    private long buffer = 0;  // unwritten bits
    private int bufferSize = 0;  // number of bits in buffer

    public BitOutputStream(OutputStream out) {
        this.out = out;
    }

    // ...
}

The main work is done by the writeBits() method, which writes the lowest \(n\) bits of value to the wrapped output stream (Listing C.84). The statement bits &= -1L >>> (64 - n) isolates the lowest \(n\) bits. The flush() method writes all remaining bits in the buffer to the output.

Listing C.84ch9โ€ฏ/โ€ฏBitOutputStream

// Write a single bit.
public void writeBit(long bits) throws IOException {
    writeBits(bits, 1);
}

// Write the n least significant bits.
public void writeBits(long bits, int n) throws IOException {
    assert n > 0 && n <= 56;
    bits &= -1L >>> (64 - n);
    buffer |= (bits << (64 - n - bufferSize));
    bufferSize += n;
    while (bufferSize >= 8) {
        out.write((int) (buffer >>> 56) & 0xff);
        buffer <<= 8;
        bufferSize -= 8;
    }
}

public void flush() throws IOException {
    if (bufferSize != 0)
        writeBits(0, 8 - bufferSize % 8);
}

c)The outline of BitInputStream is shown in Listing C.85. Bits that are read from input are buffered in the highest bits of the buffer field, and bufferSize holds the number of bits in buffer.

Listing C.85ch9โ€ฏ/โ€ฏBitInputStream

// A class for treating an InputStream as a sequence of bits.
public class BitInputStream {
    protected InputStream input;  // byte stream for input
    private long buffer = 0;      // the next unread bits
    private int bufferSize = 0;   // number of bits in buffer

    public BitInputStream(InputStream input) throws IOException {
        this.input = input;
        fillBuffer();
    }
    // ...
}

The fillBuffer() method tries to read as many bytes as possible into the buffer (Listing C.86). As long as the buffer has space for another byte (that is, if it contains \(56\) bits or less), it reads one byte from input and stores it at the appropriate position in buffer. When fillBuffer() encounters the end of input, it doesn’t throw an exception but returns immediately.

Listing C.86ch9โ€ฏ/โ€ฏBitInputStream

// Read bytes from input and store them in buffer.
private void fillBuffer() throws IOException {
    while (bufferSize <= 56) {
        int nextByte = input.read();
        if (nextByte < 0)
            break;  // end of file
        buffer |= (long) nextByte << (56 - bufferSize);
        bufferSize += 8;
    }
}

The readBits() shown in Listing C.87 first calls fillBuffer() to ensure that the buffer contains at least the requested number of bits and then extracts the highest bitCount bits from buffer and returns them to the caller. Only up to 56 bits can be read in a single call to readBits() because that’s the number of bits that are guaranteed to be available in buffer. (It wouldn’t be hard to modify readBits() to return up to 64 bits, but we optimize for short bit sequences because they are much more common when when working with compressed data.)

Listing C.87ch9โ€ฏ/โ€ฏBitInputStream

// Read a single bit.
public long readBit() throws IOException {
    return readBits(1);
}

// Read multiple bits.
public long readBits(int n) throws IOException {
    assert n > 0 && n <= 56;
    if (bufferSize < n) {
        fillBuffer();
        if (bufferSize < n)
            throw new IOException("End of stream");
    }
    long result = buffer >>> (64 - n);
    buffer <<= n;
    bufferSize -= n;
    return result;
}

[9.14]

a)The first six symbols come from Japanese, Indian, and Chinese scripts, the last three symbols are from a subset of Unicode symbols for drawing boxes. Here are the names of the symbols:

.
Symbol Code point Name
(image) 0x30ce KATAKANA LETTER NO
(image) 0xca0 KANNADA LETTER TTHA
(image) 0x76ca CJK UNIFIED IDEOGRAPH-76CA
(image) 0x5f61 CJK UNIFIED IDEOGRAPH-5F61
(image) 0x253b BOX DRAWINGS HEAVY UP AND HORIZONTAL
(image) 0x2501 BOX DRAWINGS HEAVY HORIZONTAL

b)The code point 0x1F602 falls in the fourth range and is therefore encoded using four bytes. The binary representation of 0x1F602 is 0b11111011000000010, so the byte sequence becomes

  • 11110000 10011111 10011000 10000010

or, written using hexadecimal numbers, 0xf0 0x9f 0x98 0x82.

c)Yes, UTF-8 is a prefix code. The most significant bits in the first byte are chosen in such a way that no codeword can be a prefix of a longer codeword. The corresponding binary tree is outlined in Fig. C.18.

Figure C.18. The tree structure of UTF-8

d)The encode() function in Listing C.88 takes a Unicode code point and writes its UTF-8 encoding to out. The UTF-8 encoding of the table-flip emoticon is

0xe3 0x83 0x8e 0xe0 0xb2 0xa0 0xe7 0x9b 0x8a
0xe0 0xb2 0xa0 0xe3 0x83 0x8e 0xe5 0xbd 0xa1 
0xe2 0x94 0xbb 0xe2 0x94 0x81 0xe2 0x94 0xbb 

Listing C.88ch9โ€ฏ/โ€ฏUTF8

// Convert a Unicode code point to its UTF-8 encoding.
public static void encode(int codePoint, OutputStream out)
        throws IOException {
    if (codePoint < 0 || codePoint > 0x10ffff)
        throw new IOException("Invalid code point");
    if (codePoint <= 0x7f) {
        out.write(codePoint);
    } else if (codePoint <= 0x7ff) {
        out.write(0b11000000 | (codePoint >>> 6));
        out.write(0b10000000 | (codePoint & 0x3f));
    } else if (codePoint <= 0xffff) {
        out.write(0b11100000 | (codePoint >>> 12));
        out.write(0b10000000 | ((codePoint >>> 6) & 0x3f));
        out.write(0b10000000 | (codePoint & 0x3f));
    } else {
        out.write(0b11110000 | (codePoint >>> 18));
        out.write(0b10000000 | ((codePoint >>> 12) & 0x3f));
        out.write(0b10000000 | ((codePoint >>> 6) & 0x3f));
        out.write(0b10000000 | (codePoint & 0x3f));
    }
}

[9.15]

a)The implementation of writeBCD() is shown in Listing C.89. If the total number of digits is odd, we include the 4-bit sequence 1111 in the final byte.

Listing C.89ch9โ€ฏ/โ€ฏDecimalCoder

public static void writeBCD(
        int[] digits, int n, OutputStream out)
        throws IOException {
    for (int i = 0; i < n; i += 2) {
        int d0 = digits[i];
        int d1 = (i + 1 < n) ? digits[i + 1] : 0b1111;
        out.write(d0 << 4 | d1);
    }
}

When reading BCDs, every byte in the input produces two digits, except for the last byte, which produces only one digit if n is odd (Listing C.90). The main complication compared to writing BCDs is the added error handling if either the stream ends prematurely or if an invalid codeword is encountered.

Listing C.90ch9โ€ฏ/โ€ฏDecimalCoder

static void readBCD(InputStream in, int n, int[] result)
        throws IOException {
    for (int i = 0; i < n; ) {
        int b = in.read();
        if (b == -1)
            throw new IOException("Unexpected end of file");
        int d0 = (b >>> 4) & 0xf;
        int d1 = b & 0xf;
        if (d0 >= 10 || (d1 >= 10 && i + 1 < n))
            throw new IOException("Invalid digit in BCD");
        result[i++] = (byte) d0;
        if (i < n)
            result[i++] = (byte) d1;
    }
}

b)Here is one possible Huffman code for the ten decimal digits:

.
symbol 0 1 2 3 4 5 6 7 8 9
codeword 000 001 0100 0101 0110 0111 100 101 110 111

This code requires \(3.4\) bits per digit.

c)If the length of digits[] is not a multiple of \(3\), we add one or two zeros (Listing C.91). It is possible to encode triplets of decimal digits in 10 bits without the use of multiplications, which is especially useful for hardware implementations. Two such encodings are the Chen-Ho encoding [23] and the densely packed decimal encoding [26].

Listing C.91ch9โ€ฏ/โ€ฏDecimalCoder

public static void writeDeclets(
        int[] digits, int n, BitOutputStream out)
        throws IOException {
    for (int i = 0; i < n; i += 3) {
        int d0 = digits[i];
        int d1 = (i + 1 < n) ? digits[i + 1] : 0;
        int d2 = (i + 2 < n) ? digits[i + 2] : 0;
        out.writeBits(d0 * 100 + d1 * 10 + d2, 10);
    }
}

Chapter 10

[10.1]

a)It’s easy to see that the algorithm performs exactly the same steps in both cases. For a single Match token, the inner for loop is executed once and copies \(n\) bytes before incrementing \(p\) by \(n\):

\begin{align*} \Id {output}[p+0] &= \Id {output}[p-\Id {offset}+0]\\ \Id {output}[p+1] &= \Id {output}[p-\Id {offset}+1]\\ &\dots \\ \Id {output}[p+n-1] &= \Id {output}[p-\Id {offset}+n-1]\\ p &= p + n \end{align*} For multiple Match tokens, the inner for loop is executed multiple times, each time copying a single byte and incrementing \(p\) by 1:

\begin{align*} \Id {output}[p+0] &= \Id {output}[p-\Id {offset}+0]\\ p &= p + 1\\ \Id {output}[p+0] &= \Id {output}[p-\Id {offset}+0]\\ p &= p + 1\\ &\dots \\ \Id {output}[p+0] &= \Id {output}[p-\Id {offset}+0]\\ p &= p + 1 \end{align*}

b)The token produces multiple repetition of the previous \(o\) bytes. For instance, the Match token in the sequence

  • Byte(A), Byte(B), Match(offset=2, length=5)

produces \(2.5\) additional copies of “AB”, which results in the final string “ABABABA”.

[10.2]

Listing C.92 shows direct translation of LZ77-Compress and LZ77-Decompress. During decompression, we use the instanceof operator to determine the type of each token.

Listing C.92ch10โ€ฏ/โ€ฏSimpleLZ77

static List<SimpleToken> compress(byte[] input, int maxOffset,
        int minLength, int maxLength) {
    var tokens = new ArrayList<SimpleToken>();
    for (int k = 0; k < input.length; ) {
        int bestLength = 0, bestOffset = 0;
        for (int off = 1; off <= Math.min(k, maxOffset); off++) {
            int len = 0;
            while (len < Math.min(maxLength, input.length - k)
                    && input[k - off + len] == input[k + len]) {
                len++;
            }
            if (len > bestLength) {
                bestLength = len;
                bestOffset = off;
            }
        }
        if (bestLength >= minLength) {
            tokens.add(new SimpleToken.Match(bestOffset, bestLength));
            k += bestLength;
        } else {
            tokens.add(new SimpleToken.Byte(input[k]));
            k++;
        }
    }
    return tokens;
}

static int decompress(List<SimpleToken> tokens, byte[] output) {
    int k = 0;
    for (SimpleToken token : tokens) {
        if (token instanceof SimpleToken.Byte b) {
            output[k++] = b.value();
        } else if (token instanceof SimpleToken.Match m) {
            for (int i = 0; i < m.length(); i++)
                output[k + i] = output[k - m.offset() + i];
            k += m.length();
        }
    }
    return k;
}

[10.3]

Since Huffman’s algorithm only cares about frequencies and not the objects associated with them, a Huffman tree of tokens is constructed in the same way as a Huffman tree of characters or bytes. One possible result is shown in Fig. C.19.

Figure C.19. Huffman tree for LZ77 tokens.

[10.4]

See Table C.2 for a table of integers encoded using the Elias gamma code. The advantages of the code are that small integers are encoded very efficiently and that it can handle numbers of arbitrary size. Its main disadvantage is that large integers are encoded using many bits.

Table C.2 Encoding of integers using the Elias gamma code
.
\(n\) \(n\) in binary \(\bitlen (n)-1\) codeword
\(1\) \(1_2\) \(0\) 1
\(2\) \(10_2\) \(1\) 01 0
\(3\) \(11_2\) \(1\) 01 1
\(4\) \(100_2\) \(2\) 001 00
\(5\) \(101_2\) \(2\) 001 01
\(6\) \(110_2\) \(2\) 001 10
\(7\) \(111_2\) \(2\) 001 11
\(8\) \(1000_2\) \(3\) 0001 000
\(\vdots \) \(\vdots \) \(\vdots \) \(\vdots \)
\(3410\) \(110101010010_2\) 11 000000000001 10101010010
\(\vdots \) \(\vdots \) \(\vdots \) \(\vdots \)

[10.5]

Listing C.93 shows the outline of class LZHDecoder. The main constructor takes two arguments: the input data, which is a bit stream produced by LZHEncoder, and the output stream to which the uncompressed sequence of bytes will be written. As with other Lempel-Ziv decoders, we store a certain number of previously decoded bytes in a cyclic buffer dictionary. The outLength field holds the number of bytes that have been decoded so far. We start the decompression process in decompress() by reading the two parameters of the algorithm from the stream: maxOffset is the largest offset field that can occur and blockSize the number of tokens per block. We then initialize dictionary to a cyclic buffer of size maxOffset and read all blocks until we reach the end of the input.

Listing C.93ch10โ€ฏ/โ€ฏLZHDecoder

public class LZHDecoder {
    private final BitInputStream input;
    private final OutputStream out;
    private CyclicBuffer dictionary;  // current dictionary region
    private int outLength = 0;  // number of bytes decoded so far

    public LZHDecoder(BitInputStream in, OutputStream out) {
        this.input = in;
        this.out = out;
    }

    public void decompress() throws IOException {
        int maxOffset = (int) input.readBits(32);
        int blockSize = (int) input.readBits(32);
        dictionary = new CyclicBuffer(maxOffset);
        while (decodeBlock(blockSize)) {
        }
    }

    // ...
}

For each block, we first recover the two Huffman codes for tags and offsets and then decode one tag after the other until the entire block has been recovered (Listing C.94). If the tag is \(256\), we have reached the end of the input. If it is less than \(256\), it represents a BYTE token that we write directly to the output; the write() method writes a single byte to the output stream and to dictionary. Every other tag represents a MATCH token, which we decode by recovering the offset and length fields and copying the requisite number of bytes from dictionary.

Listing C.94ch10โ€ฏ/โ€ฏLZHDecoder

private boolean decodeBlock(int blockSize) throws IOException {
    var tagCode = PrefixCode.readCode(input);
    var offsetCode = PrefixCode.readCode(input);
    for (int k = 0; k < blockSize; k++) {
        int tag = tagCode.decodeSymbol(input);
        if (tag == 256) {
            return false;  // end of input
        } else if (tag < 256) {
            write((byte) tag);
        } else {
            final int minLength = 3;
            int length = decodeInteger(tag - 257) + minLength;
            int offset = decodeInteger(offsetCode.decodeSymbol(input));
            for (int i = 0; i < length; i++)
                write(dictionary.get(outLength - offset));
        }
    }
    return true;
}

private void write(byte b) throws IOException {
    out.write(b);
    dictionary.set(outLength++, b);
}

private int decodeInteger(int bitLength) throws IOException {
    if (bitLength <= 1)
        return bitLength;
    return (1 << (bitLength - 1))
            | (int) input.readBits(bitLength - 1);
}

The decodeInteger() method that is used to read the offset and length fields decodes a single variable-length integer. Given the integer’s bit length \(n\), the number is recovered by reading the least significant \(n-1\) bits from input and then adding the most significant bit.

[10.6]

a)Two sequences are sufficient:

  • LZ4(“Around the world, a”, offset=18, length=15)
    LZ4(0xA, offset=35, length=105)

The first sequence encodes a single line without the terminating newline character. The second sequence adds the newline and three copies of the first line, each of which consists of 35 bytes.

b)The first sequence is encoded using 10 bytes. The header contains two 4-bit numbers: The first is the length of literal part (0111) and the second the length of the match 6 reduced by the minimal match length 4 (0010). The next 7 bytes contain the literal part of the sequence, followed by 2 bytes for the offset of the match (0x0006, but in little-endian order).

  • .
    Position 0 1–7 8–9
    Bytes 01110010 YABBA␣D 0x06 0x00

The second sequence is similar, but since the match length 40 is too large for the header, an additional byte is used to encode the remainder, which is

\begin{equation*} 40-15-(\text {minimal match length}) = 21. \end{equation*}

The result is

  • .
    Position 0 1 2–3 4
    Bytes 00011111 O 0x01 0x00 21

c)The output consists of a single sequence that contains all \(n\) bytes of the input. In addition to the \(n\) bytes required to encode the literal part of this sequence, the main contributor to the size of the output is the encoding of \(n\) itself, which requires \(\bigl \lceil (n-15)/255\bigr \rceil \) bytes, or approximately \(n/255\) bytes. This corresponds to a \(100/255=0.39\,\%\) increase in file size.

d)The implementation shown in Listing C.95 includes additional error checking to ensure that the program doesn’t crash even if the input data isn’t well-formed. The ensure() method verifies that a certain condition is met and throws a DecodeException if it isn’t. The top-level decode() method reads the header of the following sequence and then decodes its literal and match parts. The match part is ignored if the end of the input is reached first.

Listing C.95ch10โ€ฏ/โ€ฏLZ4Decoder

public static class DecodeException extends Exception {
}

private void ensure(boolean condition) throws DecodeException {
    if (!condition)
        throw new DecodeException();
}

public int decode() throws DecodeException {
    while (inPos < inLength) {
        int token = in[inPos++];
        decodeLiteral(token);
        if (inPos < inLength)
            decodeMatch(token);
    }
    return outPos;
}

To decode the literal part of the sequence, the decodeLiteral() method in Listing C.96 first reads the remainder of the literal’s llength field and then copies the requested number of bytes from in[] to out[]. The length field is decoded using decodeLength(). This method takes a single parameter startLength, which is either the mlength or the llength field stored in the sequence’s header. If startLength is 15, the method reads additional bytes and add them to the length until it encounters a byte whose value is less than 255. Since bytes are signed values in Java, the expression in[inPos++] & 0xff is used to convert each byte to an unsigned integer.

Listing C.96ch10โ€ฏ/โ€ฏLZ4Decoder

private void decodeLiteral(int header) throws DecodeException {
    int literalLength = decodeLength((header >> 4) & 0xf);
    ensure(inPos + literalLength <= inLength
            && outPos + literalLength <= out.length);
    System.arraycopy(in, inPos, out, outPos, literalLength);
    inPos += literalLength;
    outPos += literalLength;
}

private int decodeLength(int startLength) throws DecodeException {
    if (startLength != 15)
        return startLength;
    int length = startLength;
    while (inPos < inLength) {
        int k = in[inPos++] & 0xff;
        length += k;
        if (k != 255)
            return length;
    }
    throw new DecodeException();  // incomplete length
}

The decodeMatch() method in Listing C.97 decodes the match part of a sequence. It first reads two bytes for the offset and then decodes the remainder of the match length using decodeLength(). Afterwards, it copies the matching bytes from a previous position in out to the current position; this can usually be done using System.arraycopy(). However, if the length is greater than the offset — that is, if the match extends beyond the current position — the bytes must be copied one by one because arraycopy()’s handling of overlapping regions is incompatible with LZ4.

Listing C.97ch10โ€ฏ/โ€ฏLZ4Decoder

private void decodeMatch(int header) throws DecodeException {
    ensure(inPos + 2 <= inLength);
    int offset =
            (in[inPos] & 0xff) | ((in[inPos + 1] & 0xff) << 8);
    inPos += 2;
    if (offset == 0)    // empty match
        return;
    ensure(outPos - offset >= 0);
    int length = decodeLength(header & 0xf) + LZ4.MIN_MATCH;
    ensure(outPos + length < out.length);
    if (length > offset) {
        for (int i = 0; i < length; i++)
            out[outPos + i] = out[outPos - offset + i];
    } else {
        System.arraycopy(out, outPos - offset, out, outPos,
                length);
    }
    outPos += length;
}

Chapter 11

[11.1]

The normalization ensures that every integer has a unique internal representation, so methods like equals() know that two numbers differ if they don’t have the same number of digits. Without normalization, equals() always has to compare all digits:

public boolean equals(Object other) {
    if (!(other instanceof BigNat o))
        return false;
    for (int i = 0; i < Math.max(size, o.size; i++)) {
        if (digitOr0(i) != o.digitOr0(i))
            return false;
    }
    return true;
}

[11.2]

We need to show that \(c<2\) for the entirety of the algorithm. This is certainly true at the beginning where we initialize \(c\) to 0. Every iteration then updates the carry to \(\lfloor (x_k+y_k+c)/B\rfloor \), which lets us derive an upper bound as follows:

\begin{align*} \bigl \lfloor (x_k+y_k+c)/B\bigr \rfloor &\le \bigl \lfloor \bigl (2(B-1)+c\bigr )/B\bigr \rfloor \\ &< \bigl \lfloor \bigl (2(B-1)+2\bigr )/B\bigr \rfloor &\text {since $c<2$ by induction}\\ &= \lfloor 2B/B\rfloor = 2. \end{align*}

[11.3]

We need to show that \(-1 \le b \le 0\) for the entirety of the algorithm. This is true at the beginning where we initialize \(b\) to 0.

Under the assumption that the current value of the borrow term satisfies \(-1\le b\le 0\), we derive two bounds for the updated value. For the upper bound we have

\begin{equation*} \bigl \lfloor (x_k-y_k+b)/B\bigr \rfloor \le \bigl \lfloor (B-1 - 0 + 0) / B\bigr \rfloor = 0, \end{equation*}

and for the lower bound

\begin{align*} \bigl \lfloor (x_k-y_k+b)/B\bigr \rfloor &\ge \bigl \lfloor (0 - (B-1) - 1)/B\bigr \rfloor \\ &= \bigl \lfloor -B/B\bigr \rfloor = -1. \end{align*}

[11.4]

The translation of MultiplyByDigit is shown in Listing C.98.

Listing C.98ch11โ€ฏ/โ€ฏBigNat

public BigNat timesDigit(int y) {
    int[] result = new int[size + 1];
    long carry = 0;
    for (int i = 0; i < size; i++) {
        long tmp = (long) result[i]
                + (long) digit(i) * (long) y
                + carry;
        result[i] = (int) (tmp & DIGIT_MASK);
        carry = tmp >>> DIGIT_BITS;
    }
    result[size] = (int) carry;
    return new BigNat(result);
}

[11.5]

Let \(c_k\) be the carry at the beginning of the \(k\)th iteration. Since the carry is initialized to 0, we have \(c_0<y\). For every following iteration we have

\begin{align*} c_k &= \lfloor (x_ky+c_{k-1})/B\rfloor \\ &< \lfloor (x_ky + y)/B\rfloor && \text {by induction}\\ &= \left \lfloor \frac {x_k+1}{B}y\right \rfloor \le \left \lfloor \frac {B}{B}y\right \rfloor = y. \end{align*}

[11.6]

We have \(x<B^n\) and \(y<B^m\), so \(xy<B^nB^m<B^{n+m}\). Any number less than \(B^{n+m}\) can be written using \(n+m\) digits.

[11.7]

Avogadro’s constant can be computed as follows:

var avogadro = BigNat.fromUnsignedLong(6022140857L);
for (int i = 0; i < 14; i++)
    avogadro = avogadro.times(BigNat.TEN);

Alternatively, we can use the pow() method defined in Exercise 11.18:

var avogadro = BigNat.fromUnsignedLong(6022140857L)
        .times(BigNat.TEN.pow(14));

The digits array of avogadro contains the three base-\(2^{31}\) digits of \(N_A\):

[454574080, 781691483, 130584] 

[11.8]

The value of x is 2. The two calls to slice() first remove the most significant digit \(3\) and then the least significant digit 1, leaving the single digit \(2\).

[11.9]

No, because in this case the recursion would produce an endless loop.

[11.10]

In the first iteration we have \(r=0\) and therefore \(t=x_n<B^2\). For each of the following iterations we can use the bound \(r<y\le B-1\) to obtain

\begin{equation*} t = rB + x_i \le (B-1)B + (B-1) = B^2-1 < B^2. \end{equation*}

[11.11]

For \(x=785, y=18\) we have \(m=2, n=1\), and the algorithm requires two iterations, with a total of 6 correction steps:

\begin{equation*} \begin{array}{ccccc} i & t & \hat q & q_i & r\\ 1 & 078 & \lfloor 7 / 1\rfloor = 7 & 4 & 6\\ 0 & 065 & \lfloor 6 / 1\rfloor = 6 & 3 & 11\\ \end {array} \end{equation*}

Scaling by \(\alpha =\lfloor 9 / (1 + 1)\rfloor =4\) gives us the equivalent problem Divide\((3140, 72)\). We now have \(m=2, n=2\) and the algorithm requires three iterations and no correction steps:

\begin{equation*} \begin{array}{crccc} i & t & \hat q & q_i & r\\ 2 & 031 & \lfloor 03 / 7\rfloor = 0 & 0 & 31\\ 1 & 314 & \lfloor 31 / 7\rfloor = 4 & 4 & 26\\ 0 & 260 & \lfloor 26 / 7\rfloor = 3 & 3 & 44\\ \end {array} \end{equation*}

The true remainder \(44/\alpha =11\) is obtained by dividing the final value of \(r\) by \(\alpha \).

[11.12]

The implementation of fromDigits() in Listing C.99 is almost identical to the longFromDecimal() method. The main difference is that we are now using a variable radix and that mapping individual digits to their integer values in parseDigit() is slightly more involved.

Listing C.99ch11โ€ฏ/โ€ฏRadix

// Parse integers with a radix between 2 and 36.
public static long fromDigits(String digits, int radix) {
    if (radix < 2 || radix > 36)
        throw new NumberFormatException("Invalid radix");
    if (digits.isEmpty())
        throw new NumberFormatException("No digits");
    long value = 0;
    for (int i = 0; i < digits.length(); i++) {
        char c = digits.charAt(i);
        value = value * radix + parseDigit(c, radix);
    }
    return value;
}

private static int parseDigit(char c, int radix) {
    int digit = -1;
    if (c >= '0' && c <= '9')
        digit = c - '0';
    else if (c >= 'a' && c <= 'z')
        digit = c - 'a' + 10;
    else if (c >= 'A' && c <= 'Z')
        digit = c - 'A' + 10;
    if (digit < 0 || digit >= radix)
        throw new NumberFormatException("Invalid digit");
    return digit;
}

[11.13]

A possible implementation of toString() is shown in Listing C.100. The outer loop splits the big integer into blocks of 18 digits, and the inner loop converts each block into a string of decimal digits. Since the digits are produced from right to left, the function reverses the list of characters before returning it as a string.

Listing C.100ch11โ€ฏ/โ€ฏBigNat

// Print 'this' as decimal number.
public String toString() {
    final int blockSize = 18;
    BigNat unit = TEN.pow(blockSize);
    StringBuilder sb = new StringBuilder();
    BigNat current = this;
    do {
        var divRem = current.divideAndRemainder(unit);
        BigNat next = divRem[0];
        long remainder = divRem[1].toUnsignedLong();
        for (int i = 0; i < blockSize; i++) {
            sb.append(remainder % 10);
            remainder /= 10;
            if (remainder == 0 && next.equals(ZERO))
                break;  // omit leading zeros
        }
        current = next;
    } while (!current.equals(ZERO));
    return sb.reverse().toString();
}

[11.14]

The name XYZ27 refers to column \(24\cdot 26^2 + 25\cdot 26 + 26 1 = 16\,900\) and row \(27\). An implementation of CellName is shown in Listing C.101. The fromString() method first computes the column from the sequence of letters at the start of name and then parses the remainder of name as a decimal integer; the toString() method performs the reverse operation. In both cases, the conversion of the column name is similar to a normal radix conversion, except that the digits in this case aren’t zero-based: the numerical value of the smallest digit A is 1.

Listing C.101ch11โ€ฏ/โ€ฏCellName

// Parsing and printing spreadsheet cell names.
public record CellName(int column, int row) {
    public static CellName fromString(String name) {
        int i = 0;
        int column = 0;
        while (i < name.length() && name.charAt(i) >= 'A'
                && name.charAt(i) <= 'Z') {
            column = column * 26 + (name.charAt(i) - 'A' + 1);
            i++;
        }
        int row = Integer.parseInt(name, i, name.length(), 10);
        if (row <= 0)
            throw new IllegalArgumentException("Invalid name");
        return new CellName(column, row);
    }

    public String toString() {
        var rowStr = new StringBuilder();
        int column = this.column;
        while (column > 0) {
            rowStr.append((char) ('A' + (column - 1) % 26));
            column = (column - 1) / 26;
        }
        return rowStr.reverse().toString() + row;
    }
}

[11.15]

Since computers cannot do arithmetic in either base, we must perform the conversion in two steps. We first convert from base 11 to either a binary (long) or a base-\(2^{31}\) (BigNat) using From-Radix and then convert from this intermediate representation to base 3 using To-Radix.

[11.16]

If the signs differ, we simply compare them using Integer.compare(); otherwise, we compare their magnitudes and multiply the result by sign (Listing C.102).

Listing C.102ch11โ€ฏ/โ€ฏBigInt

public int compareTo(BigInt y) {
    if (sign != y.sign)
        return Integer.compare(sign, y.sign);
    return sign * magnitude.compareTo(y.magnitude);
}

[11.17]

a)We have \(a=4\) since there are four simpler multiplications and \(b=2\) since each sub-problem involves multiplying numbers with half the number of digits. We therefore have

\[ T(n)=O(n^{\log _2 4})=O(n^2). \]

b)Since only three multiplications are necessary, we have \(a=3\) and \(b=2\). This gives us

\[ T(n)=O(n^{\log _{2} 3})\approx O(n^{1.58}), \]

as stated in the text.

[11.18]

a)We have \(x^{43}=x^{32}x^{8}x^{2}x\), which gives us three outer multiplications. The individual terms are obtained by repeated squaring

\begin{equation*} x \xrightarrow {\text {square once}} x^2 \xrightarrow {\text {square twice}} x^8 \xrightarrow {\text {square twice}} x^{32}, \end{equation*}

so the total number of multiplications is \(3+5=8\).

b)The pow() function in Listing C.103 computes the integer power of a value of type int by iterating over the binary digits of the exponent.

Listing C.103ch5โ€ฏ/โ€ฏIntMath

// Raise 'value' to the 'n'th power.
public static int pow(int value, int n) {
    if (n < 0)
        throw new ArithmeticException("Negative exponent");
    if (n == 0)
        return 1;
    int result = 1;
    int valuePower = value;
    while (n > 1) {
        if ((n & 1) == 1)
            result *= valuePower;
        n >>>= 1;
        valuePower *= valuePower;
    }
    return result * valuePower;
}

c)The number of iterations performed by the while loop in Listing C.103 can be expressed using the bit length of \(k\):

\begin{equation*} \text {\#iterations} = \bitlen (k) - 1 = \lceil \log _2 (k+1)\rceil - 1 \end{equation*}

(See Eq. (9.1) for the definition of the \(\bitlen \) function.) In each iteration, the algorithm performs one multiplication to square the current term and one additional multiplication if the current bit is 1. We can therefore write the total number of multiplications as the sum of the number of iterations, as above, and the number of 1-bits in \(k\), which is the population count of \(k\):

\begin{equation*} \text {\#multiplications} = \lceil \log _2 (k+1)\rceil - 1 + \operatorname {popcount}(k). \end{equation*}

For \(k=43\), this formula evaluates to \(5+4=9\), which is one more than the result obtained in part (a). The additional multiplication is necessary because the first update of result in Listing C.103 is always of the form result = 1 * valuePower.

d)Since the exponent is of type int, we can again use bit operations to iterate over its binary digits. The rest of the algorithm is unchanged, except that all arithmetic operations have to be replaced with the corresponding method calls; see Listing C.104.

Listing C.104ch11โ€ฏ/โ€ฏBigNat

// Raise 'this' to the 'n'th power.
public BigNat pow(int n) {
    if (n < 0)
        throw new ArithmeticException("Negative exponent");
    if (n == 0)
        return ONE;
    var result = ONE;
    var valuePower = this;
    while (n > 1) {
        if ((n & 1) != 0)
            result = result.times(valuePower);
        n >>>= 1;
        valuePower = valuePower.times(valuePower);
    }
    return result.times(valuePower);
}

[11.19]

a)Every even two-digit number is polydivisible, so there are 45 such numbers; the smallest is 10 and the largest 98.

b)Given a list of all polydivisible numbers with \(k\) digits, all polydivisible numbers with \(k+1\) digits can be computed by appending all possible decimal digits and keeping only those numbers that are evenly divisible by \(k+1\). For an implementation, see Listing C.105.

Listing C.105ch11โ€ฏ/โ€ฏPolydivisible

// Compute a list of all polydivisible numbers.
static List<BigInt> allPolydivisible() {
    var result = new ArrayList<BigInt>();
    List<BigInt> current = new ArrayList<>();
    for (int i = 1; i < 10; i++)
        current.add(BigInt.valueOf(i));
    for (int k = 1; !current.isEmpty(); k++) {
        result.addAll(current);
        current = extend(current, BigInt.valueOf(k + 1));
    }
    return result;
}

static List<BigInt> extend(List<BigInt> current, BigInt newLength) {
    var result = new ArrayList<BigInt>();
    for (var n : current) {
        BigInt nTimes10 = n.times(BigInt.TEN);
        for (int digit = 0; digit < 10; digit++) {
            var extended = nTimes10.plus(BigInt.valueOf(digit));
            if (extended.remainder(newLength).equals(BigInt.ZERO))
                result.add(extended);
        }
    }
    return result;
}

There are 20โ€ฏ456 polydivisible numbers, and the largest one is the 25-digit number:

\begin{equation*} 3\,608\,528\,850\,368\,400\,786\,036\,725. \end{equation*}

The number 3โ€ฏ816โ€ฏ547โ€ฏ290 is the smallest polydivisible number that contains every decimal digit exactly once. Such numbers are also known as pandigital numbers; see [73].

[11.20]

a)The digits of the integer part of \(n/m\) can be obtained using a simple integer division. We can then compute each digit of the fractional part by computing \(10r/m\), where \(r\) is the remainder of the previous division (Listing C.106).

Listing C.106ch11โ€ฏ/โ€ฏDecimalFraction

// Compute the decimal expansion of x/y to n digits.
public static String decimalFraction(BigInt x, BigInt y, int n) {
    var sb = new StringBuilder();
    var divRem = x.divideAndRemainder(y);
    sb.append(divRem[0].toString()).append('.');
    n -= divRem[0].equals(BigInt.ZERO) ? 0 : sb.length() - 1;
    for (int i = 0; i < n; i++) {
        x = divRem[1];
        divRem = x.times(BigInt.TEN).divideAndRemainder(y);
        sb.append(divRem[0].toString());
    }
    return sb.toString();
}

b)The decimal expansion of \(1/998\,001\) starts with all 3-digit numbers between 0 and 999 except for 998 and then repeats itself:

\begin{equation*} 0.000\,001\,002\,003\,004\,005\,006\,007\,008\,009\,010\,\ldots {}997\,999\,000\ldots \end{equation*}

c)As in part (a), we compute the fractional part of the decimal expansion by repeatedly dividing the previous remainder by \(m\). As soon as this remainder takes on one of its previous values, all remainders and digits that follow must repeat themselves. In Listing C.107 we use a hash table remainders to keep track of every remainder that has been encountered so far and the position of the corresponding digit.

Listing C.107ch11โ€ฏ/โ€ฏDecimalFraction

// Compute the decimal expansion of x/y and determine its period.
public static String decimalFraction(BigInt x, BigInt y) {
    var divRem = x.divideAndRemainder(y);
    if (divRem[1].equals(BigInt.ZERO))
        return divRem[0].toString();
    var sb = new StringBuilder()
            .append(divRem[0].toString()).append('.');
    var remainders = new HashMap<BigInt, Integer>();
    var rem = divRem[1];
    do {
        remainders.put(rem, sb.length());
        divRem = rem.times(BigInt.TEN).divideAndRemainder(y);
        sb.append(divRem[0].toString());
        rem = divRem[1];
    } while (!remainders.containsKey(rem));
    if (!rem.equals(BigInt.ZERO))
        sb.insert(remainders.get(rem), "[").append(']');
    return sb.toString();
}

The decimal expansion of \(987\,654\,321 / 123\,456\,789\) is

\begin{equation*} 8.[000000072900000663390006036\ldots {}9285243195495713079010989019] \end{equation*}

where the repeating digits are enclosed in square brackets; the number’s period consists of 6โ€ฏ855โ€ฏ006 decimal digits.

[11.21]

a)We use a sign-magnitude representation to store durations: sign holds the sign and digits[] the magnitude in units of seconds, minutes, and so on (Listing C.108). The radix array specifies the radix of each time unit: For seconds and minutes it is \(60\), for hours \(24\), for days \(7\), and for weeks we use an arbitrarily chosen radix of 100โ€ฏ000. We will use the constants SECOND to WEEK to access to individual array entries.

Listing C.108ch11โ€ฏ/โ€ฏDuration

// A class for computing with time durations.
public class Duration implements Comparable<Duration> {
    private final int sign;  // -1, 0, +1
    private final int[] digits;  // units of time

    // The radix of each unit of time.
    private static final int[] radix = {60, 60, 24, 7, 100_000};

    // Constants for different units of time.
    private static final int
            SECOND = 0, MINUTE = 1, HOUR = 2, DAY = 3, WEEK = 4;

    // ...
}

The private constructor in Listing C.109 initializes the sign and digits fields. As in the case of big integers, we normalize durations by requiring that all digits are nonnegative and smaller than the corresponding radix and that the sign is only 0 if all digits are also 0. The implicit assumption is that the digits[] argument points to a newly allocated array that isn’t modified afterward. With this representation, negating durations and computing their absolute value is again trivial.

Listing C.109ch11โ€ฏ/โ€ฏDuration

private Duration(int sign, int[] digits) {
    this.digits = digits;
    boolean isZero = true;
    for (int digit : digits) {
        if (digit != 0) {
            isZero = false;
            break;
        }
    }
    this.sign = isZero ? 0 : sign;
}

public Duration negate() {return new Duration(-sign, digits);}
public Duration abs() {return new Duration(1, digits);}

b)Since durations are stored in normalized form, we can compare (and hash) them by comparing (and hashing) the sign and digits fields (Listing C.110). To implement the compareTo() method, we proceed exactly as for big integers: We first compare the sign of the two durations, and only if they are equal do we compare the digits, from most to least significant.

Listing C.110ch11โ€ฏ/โ€ฏDuration

public boolean equals(Object o) {
    return (o instanceof Duration d) && sign == d.sign
            && Arrays.equals(digits, d.digits);
}

public int hashCode() {
    return 31 * Integer.hashCode(sign) + Arrays.hashCode(digits);
}

public int compareTo(Duration o) {
    if (sign != o.sign)
        return Integer.compare(sign, o.sign);
    for (int i = radix.length - 1; i >= 0; i--) {
        if (digits[i] != o.digits[i])
            return sign * Integer.compare(digits[i], o.digits[i]);
    }
    return 0;
}

c)To construct the duration for a certain unit of time, we set the digits of all shorter units to 0. The remaining digits are computed by taking the remainder v % radix[i] and propagating v / radix[i] to larger units of time (Listing C.111). The listing also shows a method makeSeconds(), which creates a duration for a given number of seconds, and a method seconds(), which returns the current number of seconds. Similar methods for other units of time can be defined in the same way.

Listing C.111ch11โ€ฏ/โ€ฏDuration

// Create a duration measured in a certain unit of time.
private static Duration ofUnit(int value, int unit) {
    int sign = Integer.signum(value);
    int v = Math.abs(value);
    int[] r = new int[radix.length];
    for (int i = unit; i < radix.length; i++) {
        r[i] = v % radix[i];
        v /= radix[i];
    }
    return new Duration(sign, r);
}

// Create a duration for the given number of seconds.
public static Duration makeSeconds(int s) {return ofUnit(s, SECOND);}

// Return the number of seconds in the current duration.
public int seconds() {return digits[SECOND];}

JDK: Integer, Math
•Duration

d)To add and subtract two durations, we use algorithms that are similar to the ones for big integers; the main difference is that each digit now has its own radix. Listing C.112 shows the implementations of addDigits() and subDigits(), which add and subtract the digits of two durations without considering their signs. The subtraction algorithm uses the floorMod() and floorDiv() functions to compute the next digit and the borrow term to correctly handle negative values of tmp.

Listing C.112ch11โ€ฏ/โ€ฏDuration

// Add the digits of two durations, keeping the sign of u.
private static Duration addDigits(Duration u, Duration v) {
    int[] result = new int[radix.length];
    int carry = 0;
    for (int i = 0; i < radix.length; i++) {
        int sum = u.digits[i] + v.digits[i] + carry;
        result[i] = sum % radix[i];
        carry = sum / radix[i];
    }
    if (carry != 0)
        throw new ArithmeticException("Duration out of bounds");
    return new Duration(u.sign, result);
}

// Subtract the digits of two durations, keeping the sign of u.
private static Duration subDigits(Duration u, Duration v) {
    int[] result = new int[radix.length];
    int borrow = 0;
    for (int i = 0; i < radix.length; i++) {
        int tmp = u.digits[i] - v.digits[i] + borrow;
        result[i] = Math.floorMod(tmp, radix[i]);
        borrow = Math.floorDiv(tmp, radix[i]);
    }
    if (borrow != 0)
        throw new ArithmeticException("Duration out of bounds");
    return new Duration(u.sign, result);
}

To handle signed durations, we proceed as in the case of signed big integers in Eq. (11.17). The implementations of plus() and minus() are shown in Listing C.113.

Listing C.113ch11โ€ฏ/โ€ฏDuration

// Add two durations.
public Duration plus(Duration v) {
    if (sign == v.sign) {
        return addDigits(this, v);
    } else {
        int cmp = abs().compareTo(v.abs());
        if (cmp == 0)
            return makeSeconds(0);
        return cmp > 0 ? subDigits(this, v) : subDigits(v, this);
    }
}

// Subtract two durations.
public Duration minus(Duration v) {return plus(v.negate());}

e)To convert a duration to a given unit of time unit, we compute its fractional part (which is determined by digits at positions below unit) and its integer part (which is determined by the remaining digits) and combine the two into a single number of type double. Listing C.114 shows the implementation of totalWeeks(); other methods such as totalDays() are implemented similarly.

Listing C.114ch11โ€ฏ/โ€ฏDuration

private double total(int unit) {
    double fracPart = 0.0;
    for (int i = 0; i < unit; i++)
        fracPart = (fracPart + digits[i]) / radix[i];
    double intPart = 0;
    for (int i = radix.length - 1; i >= unit; i--)
        intPart = (intPart * radix[i]) + digits[i];
    return sign * (intPart + fracPart);
}

// Returns the duration as a fractional number of weeks.
public double totalWeeks() {return total(WEEK);}

[11.22]

a)The implementation of Archimedes algorithm in Listing C.115 starts the iteration with \(p_6\) and \(P_6\). Empirically, this program produces approximately \(0.6\) decimal digits per iteration.

Listing C.115ch11โ€ฏ/โ€ฏPiArchimedes

static double piArchimedes(int iterations) {
    double a = Math.sqrt(3) * 2;
    double b = 3;
    for (int i = 0; i < iterations; i++) {
        a = 2 * a * b / (a + b);
        b = Math.sqrt(a * b);
    }
    return (a + b) / 2;
}

[11.23]

a)

\begin{equation*} \pi \approx 4\left (\frac {4}{5}-\frac {4}{3\cdot 5^3} - \frac {1}{239} + \frac {1}{3\cdot 239^3}\right ) \approx 3.140597 \end{equation*}

b)Machin’s formula tells us that \(100\pi \approx 1600\arctan \frac {1}{5}-400\arctan \frac {1}{239}\). The two arctan functions can be approximated easily since almost all terms are 0:

\begin{align*} 1600\arctan \frac {1}{5} &\approx \left \lfloor \frac {1600}{5}\right \rfloor -\left \lfloor \frac {1600}{375}\right \rfloor =320-4=316\\ 400\arctan \frac {1}{239} &\approx \left \lfloor \frac {400}{239}\right \rfloor = 1 \end{align*} This gives us \(100\pi \approx 316-1=315\).

c)A program that computes approximations to \(U\pi \) is shown in Listing C.116. The computePi() method implements the scaled version of Machin’s formula, and arctan1overX() the scaled version of \(\arctan 1/x\).

Listing C.116ch11โ€ฏ/โ€ฏPiMachin

public static BigInt computePi(BigInt unit) {
    BigInt a = unit.times(BigInt.valueOf(16));
    BigInt b = unit.times(BigInt.valueOf(4));
    return arctan1overX(BigInt.valueOf(5), a)
            .minus(arctan1overX(BigInt.valueOf(239), b));
}

static BigInt arctan1overX(BigInt x, BigInt unit) {
    BigInt sum = BigInt.ZERO;
    BigInt xPower = x;
    BigInt xSquared = x.times(x);
    int sign = 1;
    for (int k = 0; ; k++) {
        BigInt denom = BigInt.valueOf(2 * k + 1).times(xPower);
        BigInt term = unit.dividedBy(denom);
        if (term.equals(BigInt.ZERO))
            break;
        sum = sum.plus(sign < 0 ? term.negate() : term);
        sign *= -1;
        xPower = xPower.times(xSquared);
    }
    return sum;
}

d)Approximating \(10^{10000}\pi \) using Machin’s method produces a 10โ€ฏ000-digit number that ends in \(5525637566\). The correct digits of \(\pi \) are \(5525637567\), so Machin’s method gives us 9999 correct decimal digits.