Algorithms

Menger sponge

Take the square hole from the Sierpiński carpet and extend it through a cube. Add two more tunnels at right angles. How can three tunnels, each three cubes long, remove only seven cubes?

This is the first step of the Sierpiński carpet. Eight squares surround the central hole.

Previous episode · Sierpiński carpet

Video walkthrough

From a square hole to three tunnels

Divide a cube into 3 × 3 × 3 equal cubes. Look straight at the front. Its middle square is the one we cut out of the Sierpiński carpet. Extend that square hole backward through all three layers. You have removed three small cubes.

The second tunnel runs left to right and the third runs top to bottom. All three meet at the center cube, which the first tunnel already removed. The count is 3 + 2 + 2 = 7, so 20 of the 27 cubes remain.

In Layers, compare the front, middle and back slices. After the first tunnel, every slice has eight cubes around a hole. After all three tunnels, the middle slice has only four corner cubes. The front and back still have eight each.

The carpet reappears on every outer face

Apply the same three cuts to each of the 20 remaining cubes. Every retained cube becomes a smaller copy of the first round. Two rounds leave 400 cubes. Three rounds leave 8,000.

Choose Front view to see the carpet again. At the outside face, the coordinate pointing into the cube lies in an outer third. A square there disappears only when both of the other coordinates lie in their middle thirds. That is exactly the rule for the Sierpiński carpet.

How much volume remains?

Each round keeps 20/27 of the volume it started with. After n rounds the volume is (20/27)ⁿ of the original cube. It stays positive at every finite round and tends to zero as the number of rounds grows.

RoundCubes leftVolume left
01100%
12074.1%
240054.9%
38,00040.6%

JavaScript implementation

For each small cube, count how many of its three coordinates are in the middle third. Keep it if the count is less than two. The function enumerates every retained cube and uses O(20ⁿ) time and memory.

Show executable code
function mengerCubes(rounds) {
    let cubes = [[0, 0, 0]];
    for (let level = 0; level < rounds; level++) {
        const next = [];
        for (const [x, y, z] of cubes) {
            for (let dz = 0; dz < 3; dz++) {
                for (let dy = 0; dy < 3; dy++) {
                    for (let dx = 0; dx < 3; dx++) {
                        const middle = Number(dx === 1) + Number(dy === 1) + Number(dz === 1);
                        if (middle < 2) next.push([3 * x + dx, 3 * y + dy, 3 * z + dz]);
                    }
                }
            }
        }
        cubes = next;
    }
    return cubes;
}

Sources