Algorithms

Sierpiński carpet

At every round we cut away one ninth of what remains. After four rounds, the carpet still covers more than half the starting square. What happens if we keep going forever?

Start with a solid square.

  • Area remaining 100%
  • Squares remaining 1

Video walkthrough

How to cut out the carpet

Start with a square of side length 1. Divide it into a 3 × 3 grid and cut out the center cell. Eight squares of side length 1/3 surround the hole.

In the second round, split each of those eight squares into its own 3 × 3 grid. The interactive first marks all eight centers. After the cuts, eight smaller squares surround each new hole. That makes 64 squares of side length 1/9.

Look at the top-left square after the second round. It contains the first-round pattern. The other seven squares show the same pattern. This is self-similarity.

How much area remains

Each round removes one ninth of the current area. After n rounds, (8/9)ⁿ of the starting area remains.

Every finite round leaves positive area. The Sierpiński carpet is the set that remains after infinitely many rounds. It has area zero because (8/9)ⁿ tends to zero. The boundaries of the holes and the outer edge remain.

RoundSquares remainingArea remaining
01100%
1888.9%
26479%
351270.2%
44,09662.4%

From square to cube

Cut a square tunnel through a cube along each of its three axes, then repeat in every remaining cube to get the Menger sponge. Each outer face has the pattern of a Sierpiński carpet.

JavaScript implementation

The result lists coordinates of the remaining cells on the 3ⁿ × 3ⁿ grid. Time and memory are O(8ⁿ) because the code creates and stores every remaining cell.

Show executable code
function carpet(rounds) {
    if (!Number.isInteger(rounds) || rounds < 0 || rounds > 4) {
        throw new RangeError("Choose 0 to 4 rounds");
    }
    let cells = [[0, 0]];
    for (let round = 0; round < rounds; round++) {
        const kept = [];
        for (const [x, y] of cells) {
            for (let dy = 0; dy < 3; dy++) {
                for (let dx = 0; dx < 3; dx++) {
                    if (dx === 1 && dy === 1) continue;
                    kept.push([3 * x + dx, 3 * y + dy]);
                }
            }
        }
        cells = kept;
    }
    return cells;
}

console.log(carpet(2).length); // 64

Sources