Re: irritating little problem

• To: mathgroup at smc.vnet.net
• Subject: [mg32926] Re: irritating little problem
• From: "Allan Hayes" <hay at haystack.demon.co.uk>
• Date: Wed, 20 Feb 2002 01:26:04 -0500 (EST)
• References: <a4sv9c\$ido\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Peter,
One immediately thinks of using Position as in the attempt 1 below, but this
involves a search of the list for every one of its values and is clearly
inefficent.
Much better is to attach the positions to the elements of the list and then
manipulate the result - attempt 2.

To get timings I use

n=500
vec = Table[Random[Integer, {0, n}], {10n}];

attempt 1:

pn1=(#->Position[vec,#])&/@Union[vec];//Timing

{17.63 Second,Null}

0/.pn1

{{342},{581},{2162},{2281},{2315},{3051},{3071},{3239},{3351},{4425}}

attempt2:

pn4=(#[[1,1]]->#[[All,2]]&/@
Split[Sort[
Transpose[{vec,
Range[Length[vec]]}]],#1[[1]] == #2[[1]]&]);//Timing

{0.94 Second,Null}

0/.pn4

{342,581,2162,2281,2315,3051,3071,3239,3351,4425}

- The inner lists in attempt 1 can be removed by flattening the answer.
- We could have attached the positions to the elements in attempt 1 by using
MapIndexed, but I think that this is slower.
- The advantage of attempt 1 increases with the size of n.

--
Allan

---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565

"KIMIC Weijnitz Peter" <micweij at eka.ericsson.se> wrote in message
news:a4sv9c\$ido\$1 at smc.vnet.net...
> I have a simple vector
> and I want to find the position of elements that are equal.
>
> I.e I want to test the vector and find all cases of similar elements.
>
> Brute force is not what I want, it can be a long vector.
> Best regards
> Petr W
>

```

• Prev by Date: Re: Mathematica programs to C/Fortran ?
• Next by Date: Re: Manipulating Pattern Matching ?
• Previous by thread: Re: irritating little problem
• Next by thread: Re: irritating little problem