1
$\begingroup$

I'm simulating a sequence of dice rolls by choosing a random integer between 1 and 6. I need to use FoldList to generate a function that returns a list which describes how the cumulative total varies through the generated random sequence after n tosses. How do I accomplish this?

$\endgroup$
7
  • 1
    $\begingroup$ You can also use Accumulate. However, where is your question? $\endgroup$ – Henrik Schumacher Mar 6 '20 at 20:35
  • $\begingroup$ Writing the function is the question. Sorry for the confusion. $\endgroup$ – Ray Mar 6 '20 at 21:07
  • $\begingroup$ FoldList[Plus, {1, 2, 3, 4, 5}] $\endgroup$ – Henrik Schumacher Mar 6 '20 at 21:09
  • $\begingroup$ @HenrikSchumacher Why didn't you include 6? Correct me if I'm wrong but how does this include the cumulative total after n tosses? $\endgroup$ – Ray Mar 6 '20 at 21:30
  • 1
    $\begingroup$ That was just an example to show you how to do the accumulation with FoldList. You have still to throw the dice. For example, 12 tosses: FoldList[Plus, RandomInteger[{1, 6}, 12]] Although I would recommend to use Accumulate[RandomInteger[{1, 6}, 12]]. $\endgroup$ – Henrik Schumacher Mar 6 '20 at 21:38
2
$\begingroup$

Henrik Schumacher has shown how to use FoldList to do the accumulation. All you need to get what you want is a way to generate n random integers in the ranges 1–6. You can do that with a single call to RandomInteger:

RandomInteger[{1, 6}, n]

Your function should take n, the number of tosses as it argument.

$\endgroup$
2
  • $\begingroup$ Didn't the OP ask for the cumulative total? I think the answer by Henrik Schumacher (written as a function) gives a most concise answer: RollTotal[numberOfRolls_]:= Accumulate[RandomInteger[{1,6},numberOfRolls] $\endgroup$ – Mark R Mar 7 '20 at 1:43
  • $\begingroup$ @MarkR. Yes, that's why I reference Henrik's comment. $\endgroup$ – m_goldberg Mar 9 '20 at 12:17
-1
$\begingroup$

I think you want NestList:

mylist[n_: Integer] := NestList[# + RandomInteger[{1, 6}] &, 0, n]
$\endgroup$

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