Academic work · Mathematical modeling course project
From card-game rules to a probabilistic model
I wrote code to play a solitaire variant, then ran simulations to see how the probability of winning changes with the number of stacks allowed.
- Question
- How does the chance of winning a solitaire variant change with the number of stacks allowed?
- Approach
- I coded the game in Python, simulated 100,000 games at each stack limit from 4 to 14, and compared polynomial, exponential, and logistic models of the trend.
- Result
- Wins are rare up to about seven stacks and nearly certain by thirteen. The expected value of the remaining cards falls along an S-shaped curve, which a logistic model describes with three parameters I first estimated from the graph.
01 — Rules to code
From the instructions to a program
Our instructor gave us a version of solitaire and asked us to model it. I wrote code to play the game, then ran simulations to estimate how the probability of winning changes with the number of stacks allowed.
The game, as my code plays it: a 52-card deck with ranks 0 to 12, four of each. Two cards start two stacks. When two stacks show the same rank on top, each of them gets the next card from the deck. If nothing matches, the next card starts a new stack. I lose if the number of stacks reaches the stack limit, and win if I get through the deck.
One drawn card can set off several matches in a row:
01 Draw
Stacks A and B show a 7 and a 3. I draw a 3 and start stack C; its top matches stack B. Stack A: 7. Stack B: 3. Stack C: 3.
Lines 43–44, then 20 of the listing
02 Match 1
B and C each get the next card, a 7 and a 4. Now A and B both show a 7. Stack A: 7. Stack B: 3, 7. Stack C: 3, 4.
Lines 20, 28–30 of the listing
03 Match 2
A and B each get a 9 and a 4. Now B and C both show a 4. Stack A: 7, 9. Stack B: 3, 7, 4. Stack C: 3, 4.
Lines 20, 28–30 of the listing
04 Match 3
B and C each get an 11 and a 6. No tops match, so I draw again. Stack A: 7, 9. Stack B: 3, 7, 4, 11. Stack C: 3, 4, 6.
Lines 28–30, then 20–22 of the listing
Drawn for this page to illustrate the rules; not output from the simulation. The sequence was checked against the original code. In each stack the newest card is the top, drawn lowest; amber marks matching tops.
The code is written in three basic steps:
find_matchchecks whether any stacks match.resolve_matchesupdates any matching stacks. This is more than a simple stack addition, to account for the chance of chaining matches.- The main
whileloop plays the game. It calls the match functions to check for a match or to create a new stack.
One of the biggest issues I found in testing was placing cards in the stacks. Some stacks contained only one value, while others were not updating properly. My solution was the resolve_matches function, which handles the chaining behavior of matching stacks. Separating these actions into functions produced a cleaner, more intuitive main loop.
Resolving matches, in the original code
This is my resolve_matches, exactly as submitted (lines 16 to 30 of the Game listing; the comments are mine). The numbered badges match the steps below, and the frames above point to the same lines.
· · · lines 1–15 omitted · · · def resolve_matches(): "Adds cards to matching stacks" nonlocal next_card_to_flip4 while True:1 match = find_match() if not match: return None # no more matches # need 2 cards to add to each stack, this condition is checked often to not break game if next_card_to_flip + 1 >= len(deck): return "Win" else: # place two cards2 stacks[match[0]].append(deck[next_card_to_flip])2 stacks[match[1]].append(deck[next_card_to_flip + 1])3 next_card_to_flip += 2· · · lines 31–54 omitted · · ·- Find a match.
find_match()returns the first pair of stacks whose top cards are equal, or nothing (line 20). - Deal onto the matched stacks. Each stack in the pair gets one card, the next two cards in the deck (lines 28 and 29). Line 24 first checks that two cards remain.
- Advance the deck index.
next_card_to_flipmoves forward by two (line 30). - Repeat. The
while Trueloop (line 19) looks again, because the new top cards may match something else. Whenfind_matchfinds nothing, the function returns (line 22).
Original find_match and main loop
The rest of my original Game function: lines 1 to 15, which define find_match, and lines 32 to 54, the setup and the main loop. resolve_matches, lines 16 to 30, is shown above.
def Game(max_stacks): "This is the solitaire game" stacks = [] deck = shuffled_deck(4, 13) next_card_to_flip = 0 def find_match(): "Checks to see if any stacks match" for i in range(len(stacks)): for j in range(i + 1, len(stacks)): if stacks[i][-1] == stacks[j][-1]: return i, j else: return None· · · lines 16–31 omitted · · · # initial start with two stacks stacks.append([deck[0]]) stacks.append([deck[1]]) next_card_to_flip += 2 if resolve_matches() == "Win": return "Win", stacks, 1, sum(deck[51:]) # main loop while next_card_to_flip < len(deck): # draw one card a card and add to new stack stacks.append([deck[next_card_to_flip]]) next_card_to_flip += 1 remaining_cards = deck[next_card_to_flip:] if resolve_matches() == "Win": # This if statement calls on the resolve_matches function looping the match checking return "Win", stacks, 1, sum(deck[51:]) if len(stacks) > max_stacks -1: return "Lose", stacks, len(remaining_cards), sum(remaining_cards) return "Win", stacks, 0, 002 — Simulation
From games to trends
I wrote a separate simulation function that repeatedly calls the game and keeps track of its outputs. It counts wins and losses, adds up the remaining-card counts and values, and averages those totals across the games. I ran 100,000 games as a reasonable balance between computation time and accuracy, then varied the stack limit to observe the trends.
Original simulate function
Lines 1 to 16 of my original simulate, the loop and the accumulation, and its last line. Lines 17 to 36, which compute the expected values and print the results, are omitted.
def simulate(num_games, max_stacks): wins = 0 losses = 0 total_remaining = 0 total_value_sum = 0 for _ in range(num_games): result, stacks, remaining_count, total_value = Game(max_stacks) if result == "Win": wins += 1 else: losses += 1 total_remaining += remaining_count total_value_sum += total_value· · · lines 17–36 omitted · · ·simulate(100,10)The listing ends with a sample call, simulate(100,10): 100 games with a stack limit of 10, as a demonstration. The results below come from separate runs of 100,000 games, as my report states; this listing does not itself show those runs.
My first results table recorded even stack sizes. For the graphs I simulated every stack size from 4 to 14 to have more data points to improve the model.


I see a clear association between the probability of winning and the number of stacks. Notice how the probability increases greatly with 10 stacks. The expected value of the remaining cards is calculated by summing the value of the remaining cards, then averaging over all trials. The win probability graph is almost a reflection of the remaining-card value plot, hinting that the model could be reversed to model win probability in the future.
03 — Candidate models
Finding a curve for the trend
The text in this section is lightly edited from my report.
A third-degree polynomial

At first I noticed the negative slope of the graph, which led me to try a polynomial fit. I used polyfit to generate a third-degree polynomial, with coefficients a = 1.07, b = −29.29, c = 213.2 and d = −178, in descending degree. However, notice the end behavior, where it tries to go up again. This is a sign of overfitting and makes no sense in practice. This would be good for interpolation but not for extrapolation.
Exponential decay

Since the polynomial fit did a poor job, I tried another method from class: a least-squares fit for a one-term model, y = a·bˣ, where y is the expected value of the remaining cards and x is the number of stacks. The first step is to transform the data, but when I did, there was a clear lack of linear behavior. That suggested nonlinear least squares: instead of transforming the data into a line, you minimize the sum of the squared residuals between the model and the original data. This needs an iterative numerical method, such as SciPy’s curve_fit. I found a = 736.7552 and b = 0.8236. My report states that this model does a better job than the polynomial, but that its residuals would still be poor, so it is not a good model for this data. It is clear that there is a more complex decay pattern going on.
Logistic decay

After exhausting the methods of model building from this course, and unsatisfied with the previous models, I studied types of exponential decay, since that made the most sense looking at the graph. Surprisingly, I stumbled upon a type of decay that nearly perfectly fits the data: logistic decay. It is characterized by an S-shaped curve, exactly like the plot of my data. Its bounds are easily defined and it decays to zero, which suits this data.
E[V] = L / (1 + ek(x − x₀))
L is the upper limit, x is the number of stacks, x₀ is the midpoint (the inflection point of the S-shaped decay), and k is the steepness (the decay rate).
04 — Parameter intuition
Estimating the parameters from the graph
I can intuitively guess the values just by looking at the graph of my data. The upper limit should theoretically be 312, since that is the total value of the cards in the deck. However, playing even with a small number of stacks still removes cards from the deck, so I started the model at stack size 4 with an upper bound of 285, from the data. The inflection point I could identify as about x = 9, or 9 stacks. After several tries I found that the best decay rate was 1.
Plotting these guesses gave the curve above, which follows the behavior closely. I also found that SciPy’s curve_fit can compute the coefficients for a logistic curve. These are the two sets of values in my report:
| Parameter | Chosen by hand (the plotted curve) | Optimized (reported separately) |
|---|---|---|
| L, plateau | 285 | 278.7722 |
| x₀, midpoint | 9 | 9.2261 |
| k, steepness | 1 | 1.0664 |
The optimized values closely match the ones I found intuitively. The pictured curve uses my hand-chosen values; the optimized ones are listed in my report, and I have not rerun that fit here.
Read the complete original report (PDF) · Full-size figures: overview, cubic, exponential, logistic