Newbie question here. Consider the following two functions:
f1[n_] := (
q = {0, 0};
Do[q[[RandomInteger[{1, 2}]]] += 1, n];
Return[q]
)
f2[n_] := (
q = {0, 0};
Do[k = RandomInteger[{1, 2}]; q[[k]] += 1, n];
Return[q]
)
Both seem to be doing the same thing: create a list of zeros, increment a random element $n$ times and return the list. The difference is that the first version "inlines" RandomInteger call into the indexing, while the second defines an intermediate variable k.
The function f2 works as expected, while f1 does not. For example, f1 sometimes returns lists for which sum of elements is not equal to the input n, which seems very strange.
In[357]:= f1[10]
Out[357]= {6, 7}
Can someone point out why f1 and f2 are treated differently?
f1[2] // Traceandf2[2] // Trace– kglr Aug 02 '18 at 00:23AddTois the same as withPreIncrement.) – Michael E2 Aug 02 '18 at 02:36