MathGroup Archive 1999

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: RE: easiest way to sort a list?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg18384] Re: [mg18323] RE: [mg18308] easiest way to sort a list?
  • From: gaylord at ux1.cso.uiuc.edu (richard j. gaylord)
  • Date: Wed, 30 Jun 1999 14:13:39 -0400
  • Organization: university of illinois
  • References: <7l8iv1$n5o$2@dragonfly.wolfram.com>
  • Sender: owner-wri-mathgroup at wolfram.com

> > Peter (peterw at cco.caltech.edu) wrote:
> > -------------------
> > Suppose you have a list of integers, not all distinct, say
> >       {1, 5, 3, 5, 10, 10, 1},
> >
> > and you want to obtain the list
> >
> >       {1, 5, 3, 10}
> >
> > which is the set of distinct elements but with the order preserved; i.e.,
> > the order in which the elements in the second list appear is the same as
> > the order in which it first occurs in the first list.  What is a simple
> > way to do this?  Evidently Union[] sorts the elements in canonical order,
> > which is not desirable.  My current solution is so messy that I suspect
> > there must be an easier way.
> >
> > ------------------------
> >
> > Peter,
> >
> > Robby Villegas posted a slick solution to this problem in this newsgroup.
> > See [mg8265] from 23, August 1997.
> > -----------------------
> >
> > In[1]:=
> > RestoreOrder[subset_, list_] := Last /@ Sort[ {Position[list, #, {1}, 1][[1,
> > 1]], #}& /@ subset ] ;
> > EliminateRepetition[list_List] := RestoreOrder[Union[list], list]


here's a more elegant one-liner [one-liners are always more elegant :)  ] :


In[3]:=
dog[lis_] := lis[[Sort[Flatten[Map[Position[lis, #, 1, 1] &, Union[lis]]]]]]


In[16]:=
pig = Table[Random[Integer, {1, 9}], {500000}];

In[19]:=
horse = EliminateRepetition[pig] // Timing

Out[19]=
{10.3667 Second, {9, 4, 3, 1, 2, 6, 5, 8, 7}}

In[21]:=
cow = dog[pig] // Timing  

Out[21]=
{10.25 Second, {9, 4, 3, 1, 2, 6, 5, 8, 7}}

so for a list of 500,000 integers (of which only 9 are unique) the dog
function is clearly MUCH faster than robby's solution  :)
-- 
"I would say life is pretty pointless, wouldn't you, without the movies?"
Vincent Gallo as Johnny Tempi in The Funeral (1996)


  • Prev by Date: Re: easiest way to sort a list?
  • Next by Date: Re: problems with series of multiple integrals
  • Previous by thread: Re: Re: easiest way to sort a list?
  • Next by thread: Re: Re: easiest way to sort a list?