# Iterative function

I would like to write a bit of code that does the following.

Pick a random number from 1 to 20 (inclusive)

then if that number is < 15, stop

if that number is > 15 pick 2 numbers from 1-20, and check the highest number from the pair.

do the same check, if greater than 15, pick 3 numbers, then 4 then ectara.

f[n_] := Max[RandomInteger[{1, 20}, n]]


I made this function to give me the highest result from n rolls but I'm not sure how to iterate it .

thank you

• When you pick 2 or more numbers from 1-20, are these numbers distinct or could be repeated? Commented Jul 17, 2021 at 1:53
• @OkkesDulgerci the numbers can be repeated Commented Jul 17, 2021 at 3:56
• See my edit then. Commented Jul 17, 2021 at 4:32

Set up a test function to control the iteration:

Clear[test, i]
i = 1;
test[i_] := Max[Sow[RandomInteger[{1, 20}, i]]] >= 15;


Use Sow-Reap combo to collect the results generated during the iteration, where SeedRandom is used to make the random results appear determined for the purpose of demonstration:

SeedRandom[23];
Reap[While[test[i], i++]][[2, 1]]

{{20}, {16, 5}, {11, 1, 9}}

• so it rolled a 20, then stopped, then it rolled a 16, then a 5, then stopped, then 11, 1, 9 then stopped? Commented Jul 16, 2021 at 15:38
• @Wombles Step 1：it "randomly" gets a 20, because the max is not <15, so the "random" generation continues to Step 2; it get 16 and 5, again the max is not <15 so the iteration continues to Step 3; this time the max is less than 15 so the iteration stops. Commented Jul 16, 2021 at 16:04
• Oh i see, thank you for the explanation Commented Jul 16, 2021 at 16:12

Here is an alternative approach. This generates empty list most of the time since first number might be less than 15 more often.

SeedRandom@134
list = TakeList[RandomChoice[Range@20, 10000], Range@100];
TakeWhile[list, Max@# >= 15 &]


{{19}, {4, 18}, {10, 11, 18}}

Let see next list

Take[list, 4]


{{19}, {4, 18}, {10, 11, 18}, {3, 6, 5, 7}}

Here is the length distribution

SeedRandom@134
dist = Length /@
Table[list = TakeList[RandomChoice[Range@20, 10000], Range@100];
TakeWhile[list, Max@# >= 15 &], 10000] + 1 // Tally // Sort

BarChart[dist[[All, 2]],
ChartLabels ->
Placed[{dist[[All, 1]], dist[[All, 2]]}, {Below, Above}]]


So What i ended up doing is this

f[n_] := Max[RandomInteger[{1, 20}, n]]
Tally[Sort[
Table[First[
Position[Map[f, Range[2, 100]], _?(# < 15 &)]], {10000}] /.
First[{}] -> {100}]]


because I wanted to figure out the probabilities of hitting any given stopping point.