[Date Index]
[Thread Index]
[Author Index]
Re: For Loop and Array related
*To*: mathgroup at smc.vnet.net
*Subject*: [mg58028] Re: For Loop and Array related
*From*: Bill Rowe <readnewsciv at earthlink.net>
*Date*: Thu, 16 Jun 2005 05:37:32 -0400 (EDT)
*Sender*: owner-wri-mathgroup at wolfram.com
On 6/15/05 at 5:58 AM, mchangun at gmail.com wrote:
>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?
I don't see why your code above isn't giving the result you expect. OTOH, I do know how to get the result you want without using a For loop. Specifically,
lattice=Length/@Split[Sort@Table[Random[Integer,{1,100}],{16000}]];
Will do what you want
An alternative solution would be
lattice=Count[Table[Random[Integer, {1,100}],{1600}],#]&/@Range@100;
I did a bit of quick testing which indicates the alternative I show is slower by a factor of 2-3. But it may be preferable since it can result in some values in lattice being zero while the faster method will never give a zero value.
For your stated conditions (16000 random integers between 1 and 100) it is very unlikely not to have at least one occurance of every interger from 1 to 100. And as long as every integer occurs, the two methods yield identical results.
--
To reply via email subtract one hundred and four
Prev by Date:
**Mathematica 5.1 Cumulative Normal Definition**
Next by Date:
**Re: splitting sublists**
Previous by thread:
**Re: For Loop and Array related**
Next by thread:
**Re: For Loop and Array related**
| |