# Simulating a “Coin Tossing” Game

i was wondering if i could simulate the following Coin-tossing-game in Mathematica:

Two Persons are playing "Coin-tossing" against each other. If one wins, he gives one Dollar to the other. Game continues until one Person has no money left.

Would appreciate your help :)

• Hi Joe, its doable - it would be useful for others if you could provide some code to start with. Have you tried anything so far? – e.doroskevic Apr 7 '16 at 20:00
• Yeah i tried some things, but i am failing at the basics right now. I found out how to use the IF Construct in Mathematica and i think i might have to use RandomInteger[] But i dont know how to declare Variables, for example. – Damm Joe Apr 7 '16 at 20:02
• In Mathematica you don't declare Variables. – andre314 Apr 7 '16 at 20:15
• something like this : f[x_] := x + RandomChoice[{-1, 1}]; testQ[y_] := (y > 0); NestWhileList[f, 10, testQ] ? – andre314 Apr 7 '16 at 20:34
• Changed throwing to tossing which next to flipping seems a much more standard name for the game. – gwr Apr 8 '16 at 12:24

Let's say that both players start with 10 dollars. We can represent the game state with a list:

start = {10, 10};


Create a function which plays one round of the game. There are only two possible outcomes, we can use RandomChoice to pick randomly between them:

oneRound[{x_, y_}] := RandomChoice[{{x + 1, y - 1}, {x - 1, y + 1}}]


For example oneRound[start] will give either {9, 11} or {11, 9} with equal probability. By repeatedly applying the oneRound function to the list we can simulate the game. But we also need to stop the game when one player runs out of money. So we create another function which returns True if the game can continue and False otherwise. The condition for the game to continue is that both players have more than zero dollars:

gameContinues[{x_, y_}] := x > 0 && y > 0


To simulate a full game we need some code which starts with the list start and repeatedly applies the function oneRound as long as gameContinues returns True. As Andre suggested, we can use NestWhileList for this:

result = NestWhileList[oneRound, start, gameContinues]


{{10, 10}, {11, 9}, {12, 8}, {11, 9}, ..., {18, 2}, {19, 1}, {20, 0}}

To visualise the game:

ListLinePlot[Transpose[result], PlotLegends -> {"Player 1", "Player 2"}] • Really Helpful, thanks a lot Sir Simon :) – Damm Joe Apr 8 '16 at 8:39