Re: reducing the time of constructing a List

• To: mathgroup at smc.vnet.net
• Subject: [mg57571] Re: reducing the time of constructing a List
• From: Curt Fischer <tentrillion at gmail.NOSPAM.com>
• Date: Wed, 1 Jun 2005 06:02:30 -0400 (EDT)
• References: <d7haeo\$3pa\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

marloo3 at mail15.com wrote:
> please, what is the best way to reduce the timing of the following lines, the
> source of data is:
> dat = Table[Random[Integer, {0, 10}], {100000}];
> and the purpose is to construct the List lst in the following way:
> For[i = 1, i <= 100000,
>       If [dat[[i]] == 1,
>         lst = Join[lst, {1}], lst = Join[lst, {0}]]; i++]; // Timing
>
> Out[]= {226.07 Second, Null}
> on the P4 celeron 2 Ghz , memory 382 MB ram
> thanks

Use pattern matching in some way or other!  That should be much faster
than procedural programming.

I don't know my laptop specs offhand but it has a slower processor and
perhaps slightly more memory than your machine.

In[1]:=
dat=Table[Random[Integer,{0,10}],{100000}];

In[2]:=
ans1=(dat/.n_Integer-> If[n\[Equal]1,1,0]);//Timing

Out[2]=
{0.441 Second,Null}

In[3]:=
ans2=(dat/.n_?(#!=1&)-> 0);//Timing

Out[3]=
{0.28 Second,Null}

In[4]:=
ans1==ans2

Out[4]=
True

--
Curt Fischer

• Prev by Date: Re: What is causing this error message?
• Next by Date: Re: Block vs Module
• Previous by thread: Re: reducing the time of constructing a List
• Next by thread: Re: reducing the time of constructing a List