0
$\begingroup$

I have written a function

roulette[n_,b_]:= With[{money=100,bins=Range[38]},Table[If[b == RandomChoice[bins], money += 35, money -= 1], {n}]]

to simulate n games of American roulette with a bet on b. The functions SubtractFrom and AddTo are not working as intended.

roulette[100,5] returns the result

SubtractFrom: 100 is not a variable with a value, so its value cannot be changed and similarly for AddTo. Is there a way to use += and -= within the function roulette?

Note: If I do not use the localized environment and define money = 100 external to the function roulette, it will run the simulation once, but this is problematic when I try to use roulette with starting money=100 in more complicated ways.

$\endgroup$
3
  • 1
    $\begingroup$ Replace With with Module? $\endgroup$
    – Syed
    Jan 24, 2023 at 18:07
  • $\begingroup$ I think you want "Module" and not "With" $\endgroup$ Jan 24, 2023 at 18:08
  • $\begingroup$ Module worked out great. Thanks. $\endgroup$
    – JEM
    Jan 25, 2023 at 18:00

2 Answers 2

2
$\begingroup$

You could just avoid those intermediate variables altogether:

RouletteWinLoss[betCount_] := RandomChoice[{37, 1} -> {-1, 35}, betCount];
RouletteSequence[start_, betCount_] := 
  Accumulate[Prepend[RouletteWinLoss[betCount], start]];
RouletteSequence[100, 30]

{100,99,98,97,96,95,94,93,92,91,90,89,88,87,122,121,120,119,118,117,116,115,150,149,148,147,146,145,144,143,142}

(Randomly got lucky!)

$\endgroup$
1
  • $\begingroup$ Wolfram is strong. Many ways to solve the same problem. Your example doesn't address the problem with += or -= and the With[] function but shows the versatility of the language. Thanks. +1 $\endgroup$
    – JEM
    Jan 25, 2023 at 18:00
1
$\begingroup$

Using FoldList:

Clear["Global`*"];
SeedRandom[3];
roulette[n_, b_] := FoldList[
  #1 + If[#2 == b, 35, -1] &
  , 100
  , RandomChoice[Range[38], {n}]
  ]

roulette[100, 5]
{100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, \
    83, 82, 81, 116, 115, 150, 149, 148, 147, 146, 145, 180, 179, 178, \
    177, 176, 175, 174, 173, 172, 171, 170, 169, 204, 203, 202, 201, 200, \
    199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, \
    185, 184, 183, 182, 181, 216, 215, 214, 213, 212, 211, 210, 209, 208, \
    207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, \
    193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180}

Further parametrization can be done as needed.

$\endgroup$

Your Answer

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

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