Re: position lists

• To: mathgroup at smc.vnet.net
• Subject: [mg68816] Re: position lists
• From: "dkr" <dkrjeg at adelphia.net>
• Date: Sat, 19 Aug 2006 00:41:42 -0400 (EDT)
• References: <ebujvu\$6lu\$1@smc.vnet.net><ec3r9m\$2o5\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Peter,

You may be able to speed things up a bit by substituting
Range[Length@a] for Ordering[a] in Pos[4].

In[1]:=
a=Table[Random[Integer,{1,20}],{1000000}];
In[2]:=
Timing[Flatten /@ (Reap[(MapThread[Sow, {#1, a[[#1]]}] &
)[Ordering[a]],
Range[20]][[2]] /. {} -> {{0}});]
Out[2]=
{3.58 Second,Null}
In[3]:=
Timing[Flatten /@ (Reap[(MapThread[Sow, {#1, a[[#1]]}] &
)[Range[Length@a]],
Range[20]][[2]] /.{} -> {{0}});]
Out[3]=
{2.61 Second,Null}

dkr

Peter Pein wrote:

> I compared some different approaches to this task.
>
> the obvious one, which you do not like:
> Pos[1][a_, n_] := Flatten /@ (Position[a, #1] & ) /@ Range[n] /. {} -> {0};
>
> one with Case[]:
> Pos[2][a_, n_] := Module[{ao = Ordering[a], as},
>      as = a[[ao]]; (Cases[Transpose[{as, ao}], {#1, x_} :> x] & ) /@
>         Range[n] /. {} -> {0}];
>
> this one uses Pick[]
> Pos[3][a_, n_] := Module[{ao = Ordering[a], as},
>       as = a[[ao]]; (Pick[ao, as, #1] & ) /@ Range[n]] /. {} -> {0};
>
> Sow/Reap:
> Pos[4][a_, n_] := Flatten /@
>     (Reap[(MapThread[Sow, {#1, a[[#1]]}] & )[Ordering[a]],
> Range[n]][[2]] /.
>      {} -> {{0}})
>
> and the Sow/Reap variant by "dkr":
> Pos[5][a_, n_] := Flatten[Reap[MapIndexed[Sow[#2[[1]], #1] & , a],
> Range[n]][[
>       2]] /. {} :> {{0}}, 1]
>
> The winner is the fourth version.
>
> See
> http://people.freenet.de/Peter_Berlin/Mathe/Igor_Pos.nb
>
> or if you're sitting in front of a box without Mathematica/MathReader:
>
> http://people.freenet.de/Peter_Berlin/Mathe/Igor_Pos.pdf
>
>
> Peter

```

• Prev by Date: Re: memory issues
• Next by Date: Re: Re: distance function
• Previous by thread: Re: position lists
• Next by thread: distance function