Group Abstract Group Abstract

Message Boards Message Boards

0
|
3.2K Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

How to set a value to an Array?

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.

In[1]:= Do[
 Clear[c];
 cArr = Array[c, 4];(* out--> {c[1],c[2],c[3],c[4]}*)
 Evaluate[cArr] = ConstantArray[0, 4];(* all c[i] = 0 *)

 Clear[c];
 Evaluate[cArr] = ConstantArray[7, 4]; (* all c[i] = 7 *)

 , 3] (*looping can return unexpected error message*)

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.

In[2]:= Definition[cArr]
Out[2]= "cArr = {c[1], c[2], c[3], c[4]}"

In[3]:= cArr
Out[3]= {7, 7, 7, 7}

In[4]:= {c[3], c[5]}
Out[4]= {7, c[5]}
POSTED BY: Raspi Rascal

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......*)
POSTED BY: Raspi Rascal
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard