All symbolic entries of the array cArr should be set to 0, i.e. c(i)=0 for all i. Later they should be set to 7, i.e. c(i)=7 for all i. Desired effect: within the Do -loop I need to access individual entries like c(3) to be 0, and later to be 7, and then looped.
The above suggested code produces the desired effect, okay. But is there any more elegant coding style to get the desired effect? For less complexity, I could get rid of the placeholder name cArr, sure. In any case, the use of Clear and Evaluate seems awkward. I can’t complain, all c(i) are 0, later they all are 7, and the looping doesn’t return any error message, as desired.
Obviously I am not very experienced working with arrays (and procedural programming). Anywho, if I may, I encountered the above HowTo-problem when translating an old PASCAL program to Wolfram L code, the famous birthday paradoxon. Here is my working translation with the Array used in the Do-loop, I am proud enough that my translation works and is succinct. First time ever that I made use of the Catch[Throw[]] idiom or even Break, all thanks to the great Wolfram L documentation which suggests related vocab items in the Guides and the Tutorials:
n = 30000;(*number of simulated years, slow code*)
k = 23;(*number of persons having birthday in a year*)
count = 0;(*counts the years in which 2 out of 23 persons shared a birthday*)
Do[
(Clear[anzahl];
Evaluate[Array[anzahl, 365]] = ConstantArray[0, 365];
gemgebtag = False;
gemgebtag = Catch[
Do[
(bday = RandomInteger[{1, 365}];
anzahl[bday]++;
If[anzahl[bday] > 1, Throw[True]]
), k]
];
If[gemgebtag == True, count++]
), n];
h = N[count/n] (*Out = 0.5073......*)
In the above Do-loop the array gets destroyed and rebuilt 10000 times. Doesn’t sound optimal to me. Of course there is a functional programming version, and it is much more efficient (but that’s not what this thread is about), my code too:
n = 1000000; (* huge number, fast code *)
k = 23;
count = 0;
Do[
(kbdays = RandomInteger[364, k];
If[Length@Union@kbdays != Length@kbdays, count++]
), n];
N@(count/n) (*Out = 0.5073......*)