Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!usc!ucsd!ogicse!intelhf.hf.intel.com!agora!markb From: markb@agora.uucp (Mark Biggar) Newsgroups: comp.lang.perl Subject: Re: Uniq, anyone? Message-ID: <1990Oct13.182400.22738@agora.uucp> Date: 13 Oct 90 18:24:00 GMT References: <1990Oct12.075314.15054@utgard.uucp> Distribution: na Organization: Open Communication Forum Lines: 30 In article J Greely writes: >In article <1990Oct12.075314.15054@utgard.uucp> chris@utgard.uucp > (Chris Anderson) writes: >>On occasion, I find myself wanting something on the order of: >> @foo = (1,1,2,2,3,3); >> @bar = &uniq (@foo); > >This seems to do it, although it strips null fields out entirely (I >call that a feature, myself): > >sub uniq { > local($o); > grep(($_ ne $o) && defined($o = $_),sort @_); >} This requires sorting the list before uniq'ing it, which make the algorithm nlogn. The following algorithm is better: sub uniq { local(%item) = (); for (@_) { $item{$_} = 1; } keys(%item); } This produces an unsorted result that can of course can be sorted. -- Perl's Maternal Uncle Mark Biggar