Re: position lists
- To: mathgroup at smc.vnet.net
- Subject: [mg68778] Re: position lists
- From: Peter Pein <petsie at dordos.net>
- Date: Fri, 18 Aug 2006 03:12:34 -0400 (EDT)
- References: <ebujvu$6lu$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
rych schrieb:
> have
> In: a = {1, 1, 2, 2, 1, 4}
> want
> {{1, 2, 5}, {3, 4}, {0}, {6}};
>
> more effectively than just
> In: Position[a, #] & /@ Range[4]
> Out: {{{1}, {2}, {5}}, {{3}, {4}}, {}, {{6}}}
>
> Ideas? Known one-liners?
> Thanks
> Igor
>
Hi Igor,
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