Project Euler Lab - Problem 595

#595 - Incremental Random Sort

● AppliedOfficial difficulty: 28%ApproximationTier B - browser, with the efficient algorithmNot viewed
↖ Euler Lab

A deck of cards numbered from \(1\) to \(n\) is shuffled randomly such that each permutation is equally likely.

The cards are to be sorted into ascending order using the following technique:

  1. Look at the initial sequence of cards. If it is already sorted, then there is no need for further action. Otherwise, if any subsequences of cards happen to be in the correct place relative to one another (ascending with no gaps), then those subsequences are fixed by attaching the cards together. For example, with \(7\) cards initially in the order 4123756, the cards labelled 1, 2 and 3 would be attached together, as would 5 and 6.
  1. The cards are 'shuffled' by being thrown into the air, but note that any correctly sequenced cards remain attached, so their orders are maintained. The cards (or bundles of attached cards) are then picked up randomly. You should assume that this randomisation is unbiased, despite the fact that some cards are single, and others are grouped together.
  1. Repeat steps 1 and 2 until the cards are sorted.

Let \(S(n)\) be the expected number of shuffles needed to sort the cards. Since the order is checked before the first shuffle, \(S(1) = 0\). You are given that \(S(2) = 1\), and \(S(5) = 4213/871\).

Find \(S(52)\), and give your answer rounded to \(8\) decimal places.

This problem is taken from Project Euler, Problem 595.
Problem text © Project Euler, licensed under CC BY-NC-SA 4.0. Original: projecteuler.net/problem=595. Published Sunday, 19th March 2017, 01:00 am. Solved by 767 members at time of mirroring.

Learning mode

Pick how much scaffolding you want. Your choice is remembered per problem.

Scratchpad

Mathematical notes, formulas, pseudocode, hypotheses, complexity notes. Saved automatically with your progress.

Python workbench

Tier B - browser, with the efficient algorithm
Runs in the browser only with the intended efficient algorithm; a naive loop will hit the timeout.

Real Python (Pyodide) in a sandboxed Web Worker - no network, no filesystem, no DOM access. Ctrl/Cmd+Enter runs. Escape leaves the editor. Stop terminates the worker.

Python runtime not loaded (it boots on first run - a one-time local load).

Check your answer

Answers are checked against a salted hash held in a separate file - not printed in this page. This prevents accidental spoilers; it is not cryptographic protection (see the build notes).

Progressive hints

Confidence

Low confidence schedules this problem for spaced review, even if you solved it.

Reference solution

Spoiler
The complete original explanation (interpretation, naive approach, insight, proof, complexity, Python implementation, tests, common mistakes, alternatives) is hidden and lazy-loaded. Reveal it only after a meaningful attempt - the struggle is where the learning happens.