Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Finding unique elements in an array

by pelagic (Curate)
on Mar 15, 2005 at 13:28 UTC ( #439619=note: print w/ replies, xml ) Need Help??

in reply to Finding unique elements in an array

Please ignore:
I don't remember where I pinched this one, it might have been around here somewhere ;-)
This shows some different ways to do it and benchmarks:

use Benchmark; my @list; for ( 0..9999 ) { push @list, sprintf "%d", 100 * rand ; } timethese( 1000, { 'keys_map_1' => sub { my @uniq = keys %{{ map {$_ => 1} + @list }}; }, 'keys_map_undef' => sub { my @uniq = keys %{{ map {$_ => un +def} @list }}; }, 'grep_seen' => sub { my %seen; my @uniq = grep ! $seen +{$_}++, @list; }, } ); __END__ Benchmark: timing 1000 iterations of grep_seen, keys_map_1, keys_map_u +ndef... grep_seen: 15 wallclock secs (14.86 usr + 0.01 sys = 14.87 CPU) +@ 67.23/s (n=1000) keys_map_1: 50 wallclock secs (46.78 usr + 0.83 sys = 47.61 CPU) +@ 21.00/s (n=1000) keys_map_undef: 43 wallclock secs (42.16 usr + 0.94 sys = 43.09 CPU) +@ 23.21/s (n=1000)
The benchmark results are very much dependant of the size of the array. I took a 10,000 items array as an example.

To post something reasonable that does implement uniq as in OP's question, here's my solution (somewhat similar to Joost's):
my @b = map {$a[$_] eq $a[$_ + 1] ? () : $a[$_]} 0..$#a;


Comment on Re: Finding unique elements in an array
Select or Download Code
Replies are listed 'Best First'.
Re^2: Finding unique elements in an array
by ikegami (Pope) on Mar 15, 2005 at 15:51 UTC
    None of these perform the function of uniq as the parent requested. uniq only looks at the previous item, not all previous items.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://439619]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2016-02-13 17:33 GMT
Find Nodes?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

    Results (442 votes), past polls