Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: For Loop and Array related

  • To: mathgroup at
  • Subject: [mg57989] Re: [mg57971] For Loop and Array related
  • From: Andrzej Kozlowski <andrzej at>
  • Date: Thu, 16 Jun 2005 05:35:46 -0400 (EDT)
  • References: <>
  • Sender: owner-wri-mathgroup at

On 15 Jun 2005, at 18:58, mchangun at 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.

The reason why your code does not work is that Lattice[[Random 
[Integer, {1, 100}]]]++ actually calls Random[Integer, {1, 100}]  
twice and the two values you get are not the same (unlike what you  

As for a more Mathematica like code, load in the discrete Math packages

<< discretemath`

we initialize your lattice

Lattice = Table[0, {n, 100}];

And now we do the random increasing

Timing[p = With[{s = Prepend[Table[0, {99}], 1]},
      Nest[#1 + RandomPermutation[s] & , Lattice, 1600]]; ]

{0.7715100000000001*Second, Null}

The total sum is indeed 1600:


We look at the first 20 entries to see what happened to them:

Take[p, 20]

{16, 14, 13, 15, 18, 14, 15, 19, 17, 10, 22, 16, 12, 17,
   12, 14, 11, 23, 15, 22}

One more thing. I have no idea why

<< discretemath`

loads all discrete math packages. I noticed Maxim doing so I tried it  
and it worked this but I don't think it is a documented feature. Does  
anyone know?
Of course what really is needed above is only the Combinatorica  
package and the normal, documented way of reading it in is


Andrzej Kozlowski

Chiba, Japan

  • Prev by Date: Re: Write/WriteString -- writing delimited txt to a stream?
  • Next by Date: Re: Randomness Test
  • Previous by thread: Re: For Loop and Array related
  • Next by thread: Re: For Loop and Array related