The expected number of loops for 50 strings is 2.94

With 50 strings, the expected number of loops is about 2.94. That answers the whole puzzle 3Blue1Brown posted in May, and if all you wanted was the number, you could stop reading. Jarom Hulet solved it on Towards Data Science three ways: a brute-force probability tree, a closed-form sum, and a Monte Carlo simulation in Python. I want the PHP version, because the part I care about is what a simulation actually has to model, and how little of that you need on a WordPress host.

The expected number of loops without simulating

With S strings in the box there are 2S loose ends. You pick one end, and the second pick chooses among the 2S-1 ends that are left. Exactly one of those is the partner of the end in your hand, so a round closes a loop with probability 1/(2S-1).

The process always runs exactly S rounds. Tying two strings into one longer string leaves one fewer string in the box, and closing a loop also leaves one fewer, because the loop comes out. Fifty strings means fifty rounds, and the last round always closes a loop, since both remaining ends belong to the same string.

Hulet leans on the rounds being independent before adding the per-round expectations. They are, for loop counting, but the sum doesn’t need that. Linearity of expectation is unconditional and works on dependent events too. All the sum needs is that a round with S strings in the box closes a loop with probability 1/(2S-1), and that follows from counting ends. The model is done.

function bbioon_exact_loops( int $strings ): float {
    $sum = 0.0;
    for ( $s = 1; $s <= $strings; $s++ ) {
        $sum += 1 / ( 2 * $s - 1 );
    }
    return $sum;
}

bbioon_exact_loops( 50 ) returns 2.9377, which is the ~2.94 Hulet gets by plugging 50 into the same sum. It’s the odd harmonic series, H(2n) minus half of H(n) if you like identities, and it grows like half the natural log of the string count plus a constant. So 500 strings gets you about 4.1 loops. Ten times the box buys a bit more than one extra loop.

Where a literal port goes wrong

His repo splits the simulation into helper functions (create_strings, select_ends, tie_ends) and imports numpy to average an array. Port that structure to PHP and you inherit three problems.

  • A dependency for an average. The mean is array_sum() over count(). On shared hosting that’s a fight you don’t need, and a lot of WordPress hosts won’t run Python at all, while WP-CLI is already sitting there.
  • Helpers that track every string end. Each array splice is a place to be off by one, and a mistake in the merge logic doesn’t throw anything. It just shifts the answer by a few hundredths, which is the same size as the error you’re trying to measure.
  • Dated randomness. rand() draws from the global Mersenne Twister state, which every other rand() call in the request advances, and the PHP manual says its values must not be used where they need to be unguessable, pointing to random_int() for that. For a toy simulation mt_rand() is fine and faster. The habit is what matters, since the file you paste a snippet into eventually grows a coupon generator.

This is also where the article’s “without AI” framing lands for me. Ask an assistant to port that script and I’d expect the literal version back, helpers and import and all, because porting is a translation job and translation preserves structure. Noticing that you don’t need the strings at all is the modeling step, and a puzzle is a cheap place to practice it.

One function, one draw per round

Once a round with S strings is one draw with probability 1/(2S-1), the simulation stops needing strings, ends, or arrays.

<?php
function bbioon_simulated_loops( int $strings, int $runs = 10000 ): float {
    $total = 0.0;
    for ( $r = 0; $r < $runs; $r++ ) {
        $loops = 0;
        for ( $s = $strings; $s >= 1; $s-- ) {
            // S strings: 2S ends, 2S-1 second picks, one closes a loop
            $loops += (int) ( 1 === random_int( 1, 2 * $s - 1 ) );
        }
        $total += $loops;
    }
    return $total / $runs;
}

echo bbioon_simulated_loops( 50 ), PHP_EOL;

The detail I like is the edge case. When one string is left, 2S-1 is 1, so random_int(1, 1) returns 1 and the same line counts the loop that’s guaranteed. There’s no special case, because the formula already contains it.

Save it as loops.php and run it with wp eval-file loops.php --skip-wordpress. Per the WP-CLI docs, that flag loads and executes the file without loading WordPress, which is right for a script that touches no WP APIs. You can run it on a production store without booting a single plugin or touching the database.

Run it twice and you get two different estimates of the same expected number of loops. Hulet’s 10,000-run Python version printed 2.95 against the exact 2.94, and that gap is roughly what 10,000 runs buys you. That’s the trade in Monte Carlo: an estimate you can’t audit line by line, against a sum you can. His harder variant, the average loop circumference, is where the trade flips, because string lengths do depend on earlier rounds, and he couldn’t find a closed form for that one, though he’s careful to say one might exist. When there’s no formula, the estimating script is the whole solution.

Ten thousand runs of fifty draws is half a million random_int() calls, fine in a terminal and wrong in a request. The rule generalizes: store math with this shape, like the Monte Carlo stock forecasts I’ve written about before, belongs in a cron job or a CLI run that saves its result, not in a page load, because a busy loop holding a PHP-FPM worker is one of the things that makes checkouts slow. If you have a heavy calculation like that on a WooCommerce site and want it off the request path, that’s the kind of work I take on.

author avatar
Ahmad Wael
I'm a WordPress and WooCommerce developer with 15+ years of experience building custom e-commerce solutions and plugins. I specialize in PHP development, following WordPress coding standards to deliver clean, maintainable code. Currently, I'm exploring AI and e-commerce by building multi-agent systems and SaaS products that integrate technologies like Google Gemini API with WordPress platforms, approaching every project with a commitment to performance, security, and exceptional user experience.

Leave a Comment