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 :)

  • $\begingroup$ 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? $\endgroup$ Apr 7, 2016 at 20:00
  • $\begingroup$ 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. $\endgroup$
    – Damm Joe
    Apr 7, 2016 at 20:02
  • 1
    $\begingroup$ In Mathematica you don't declare Variables. $\endgroup$
    – andre314
    Apr 7, 2016 at 20:15
  • $\begingroup$ something like this : f[x_] := x + RandomChoice[{-1, 1}]; testQ[y_] := (y > 0); NestWhileList[f, 10, testQ] ? $\endgroup$
    – andre314
    Apr 7, 2016 at 20:34
  • $\begingroup$ Changed throwing to tossing which next to flipping seems a much more standard name for the game. $\endgroup$
    – gwr
    Apr 8, 2016 at 12:24

1 Answer 1


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"}]

enter image description here

  • $\begingroup$ Really Helpful, thanks a lot Sir Simon :) $\endgroup$
    – Damm Joe
    Apr 8, 2016 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.