Re: For Loop and Array related

*To*: mathgroup at smc.vnet.net*Subject*: [mg58010] Re: For Loop and Array related*From*: Curt Fischer <tentrillion at gmail.NOSPAM.com>*Date*: Thu, 16 Jun 2005 05:36:28 -0400 (EDT)*References*: <d8oucl$t6q$1@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

mchangun at gmail.com wrote: > Hi All, > > I have an array with 100 elements, all set to zero initially. Then I > want to randomly choose one element and increase its value by one, and > repeat this 16000 times. Here is my code: > > Lattice = Table[0, {n, 100}]; > For[i = 1, i = 16000, i++, Lattice[[Random[Integer, {1, 100}]]]++] > > So now if I add all the elements in the list Lattice together, I should > get 16000 (I use Total[Lattice] to get the sum of the list). But this > doesn't happen, and strangely, each time I run this, the sum of the > list is different! What am I doing wrong? > > Also I'm aware that a lot of Mathematica newbies try and write code > like it were C++ and I think i've fallen into this trap as well. So is > there a different (more Mathematica) way which I can implement the > above? > > Thanks in advanced. I think the one-line (two lines if you count loading the Statistics`DataManipulation package, which you need to use the CategoryCounts function) method below is easier to implement what you want. The idea is that for your problem, you just need to generate a 16,000 element list giving the locations in the 100 element list that are augmented at each step. The number of times a location appears in the 16,000-member list is the final value of that location in the 100-member list, since everything starts at zero. You don't need to use For loops, which I always find confusing in Mathematica. In[1]:= << "Statistics`DataManipulation`" In[2]:= ans = CategoryCounts[Table[Random[Integer, {1, 100}], {16000}], Range[100]]; In[3]:= ans Out[3]= {16, 12, 20, 15, 20, 18, 15, 17, 16, 19, 14, 14, 15, 17, 20, 11, 13, 18, 13, 16, 14, 12, 17, 16, 13, 19, 13, 17, 10, 15, 22, 12, 20, 23, 18, 18, 21, 21, 20, 17, 16, 12, 18, 9, 16, 17, 12, 13, 16, 22, 16, 16, 17, 16, 23, 22, 16, 20, 8, 15, 16, 9, 11, 20, 10, 14, 14, 17, 14, 11, 13, 14, 13, 22, 21, 18, 19, 15, 13, 15, 19, 21, 17, 16, 12, 18, 17, 14, 12, 15, 12, 14, 10, 14, 16, 15, 18, 28, 10, 26} In[4]:= Plus @@ ans Out[4]= 16000