Re: position lists
- To: mathgroup at smc.vnet.net
- Subject: [mg68717] Re: position lists
- From: dimmechan at yahoo.com
- Date: Thu, 17 Aug 2006 04:18:25 -0400 (EDT)
- References: <ebujvu$6lu$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Dear Igor, You can achieve what you want with a little modification of what you thought (copy and paste the inputs to your notebook) In[1]:= Clear["Global*"] In[2]:= a={1,1,2,2,1,3,3,3,4,4,7}; In[3]:= Map[Position[a,#]&,Range[Max[a]]] Out[3]= {{{1},{2},{5}},{{3},{4}},{{6},{7},{8}},{{9},{10}},{},{},{{11}}} In[4]:= Map[Flatten,%] Out[4]= {{1,2,5},{3,4},{6,7,8},{9,10},{},{},{11}} In[5]:= %//.{x___,{},y___}\[Rule]{x,{0},y} Out[5]= {{1,2,5},{3,4},{6,7,8},{9,10},{0},{0},{11}} As an one-liner function: In[6]:= f[lst_List] := Map[Flatten, Map[Position[lst, #] &, Range[Max[lst]]]] //. \ {x___, {}, y___} -> {x, {0}, y} In[7]:= f[{1,1,2,2,1,3,3,3,4,4,7}] Out[7]= {{1,2,5},{3,4},{6,7,8},{9,10},{0},{0},{11}} Another function that do what you want is the following: In[8]:= g[lst_List]:=Module[{c},c= Map[Flatten,Map[Position[ lst,#]&, Range[Max[lst]]]];ReplacePart[c,{0},Position[c,{}]]] In[9]:= g[a] Out[9]= {{1,2,5},{3,4},{6,7,8},{9,10},{0},{0},{11}} However, both functions need considerable time for bigger lists. In[10]:= list = Table[Random[Integer, {0, 10000}], {10000}]; In[20]:= Timing[f[list]][[1]] Out[20]= 24.718 Second In[28]:= Timing[g[list]][[1]] Out[28]= 27.719 Second Certainly, there are other function that achieve your goal in less time. Anyway, I hope you will find the above, helpful. Regards, Jim